串联字符串和

2024-09-27 23:15:51 发布

您现在位置:Python中文网/ 问答频道 /正文

我想连接整数和字符串值,其中整数在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']]

Tags: 字符串代码in列表forrange整数attr
2条回答

使用下面的嵌套列表:

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

将行abc=[[attr[i]+counts[i][j]]]更改为abc=[[attr[i]+':'+str(counts[i][j])]]

相关问题 更多 >

    热门问题