Python 连接字符串和int

Python 连接字符串和int,python,string,list,Python,String,List,我想连接整数和字符串值,其中整数在2D列表中,字符串在1D列表中 ['VDM', 'MDM', 'OM'] 上面提到的列表是我的字符串列表 [[1, 2, 3, 4, 5], [1, 2, 3, 4, 5], [1, 2, 3, 4, 5]] 上面提到的列表是我的整数列表 我尝试过以下代码: for i in range(numAttr): for j in range(5): abc=[[attr[i]+counts[i][j]]] print(abc) 这里nu

我想连接整数和字符串值,其中整数在2D列表中,字符串在1D列表中

['VDM', 'MDM', 'OM']
上面提到的列表是我的字符串列表

[[1, 2, 3, 4, 5], [1, 2, 3, 4, 5], [1, 2, 3, 4, 5]]
上面提到的列表是我的整数列表

我尝试过以下代码:

for i in range(numAttr):
    for j in range(5):
        abc=[[attr[i]+counts[i][j]]]
print(abc)
这里numAttr是第一个1D列表中的元素数。第二个2D列表是一个静态列表,即对于任何数据集,2D列表都不会更改

上面显示错误的代码:

TypeError: can only concatenate str (not "int") to str
我想要一个如下所示的列表输出:

[['VDM:1','VDM:2','VDM:3','VDM:4','VDM:5'],['MDM:1','MDM:2','MDM:3','MDM:4','MDM:5'],['OM:1','OM:2','OM:3','OM:4','OM:5']]

将行
abc=[[attr[i]+counts[i][j]]]
更改为
abc=[[attr[i]+':'+str(counts[i][j])]
使用下面的嵌套列表:

>>> l = ['VDM', 'MDM', 'OM']
>>> l2 = [[1, 2, 3, 4, 5], [1, 2, 3, 4, 5], [1, 2, 3, 4, 5]]
>>> [[a + ':' + str(b) for b in c] for a,c in zip(l, l2)]
[['VDM:1', 'VDM:2', 'VDM:3', 'VDM:4', 'VDM:5'], ['MDM:1', 'MDM:2', 'MDM:3', 'MDM:4', 'MDM:5'], ['OM:1', 'OM:2', 'OM:3', 'OM:4', 'OM:5']]
>>> 
或:

或:

或f字符串(版本>=3.6):


我更喜欢f字串:D@PatrickArtner我也是,只是担心OP会说“it gives error”,因为python<3.6不能处理f字符串,无论如何都会edit@PatrickArtner哈哈,我喜欢你如何格式化你删除的答案:PIf不是f字串,然后只是:
[[{}:{}。格式化(a,b)]…]
很好…@JonClements哦,是的
>>> l = ['VDM', 'MDM', 'OM']
>>> l2 = [[1, 2, 3, 4, 5], [1, 2, 3, 4, 5], [1, 2, 3, 4, 5]]
>>> [['{}:{}'.format(a, b) for b in c] for a,c in zip(l, l2)]
[['VDM:1', 'VDM:2', 'VDM:3', 'VDM:4', 'VDM:5'], ['MDM:1', 'MDM:2', 'MDM:3', 'MDM:4', 'MDM:5'], ['OM:1', 'OM:2', 'OM:3', 'OM:4', 'OM:5']]
>>> 
>>> l = ['VDM', 'MDM', 'OM']
>>> l2 = [[1, 2, 3, 4, 5], [1, 2, 3, 4, 5], [1, 2, 3, 4, 5]]
>>> [['%s:%s' % (a, b) for b in c] for a,c in zip(l, l2)]
[['VDM:1', 'VDM:2', 'VDM:3', 'VDM:4', 'VDM:5'], ['MDM:1', 'MDM:2', 'MDM:3', 'MDM:4', 'MDM:5'], ['OM:1', 'OM:2', 'OM:3', 'OM:4', 'OM:5']]
>>> 
>>> l = ['VDM', 'MDM', 'OM']
>>> l2 = [[1, 2, 3, 4, 5], [1, 2, 3, 4, 5], [1, 2, 3, 4, 5]]
>>> [[f'{a}:{b}' for b in c] for a,c in zip(l, l2)]
[['VDM:1', 'VDM:2', 'VDM:3', 'VDM:4', 'VDM:5'], ['MDM:1', 'MDM:2', 'MDM:3', 'MDM:4', 'MDM:5'], ['OM:1', 'OM:2', 'OM:3', 'OM:4', 'OM:5']]
>>>