首页 > 解决方案 > 连接字符串和整数

问题描述

我想连接整数和字符串值,其中整数在二维列表中,字符串在一维列表中。

['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 列表中的元素数。第二个二维列表是一个静态列表,即对于任何数据集,二维列表都不会改变。

上面显示错误的代码:

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']]

标签: pythonstringlist

解决方案


使用下面的嵌套列表推导:

>>> 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']]
>>> 

或者:

>>> 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']]
>>> 

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

>>> 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']]
>>> 

推荐阅读