python - 连接字符串和整数
问题描述
我想连接整数和字符串值,其中整数在二维列表中,字符串在一维列表中。
['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']]
解决方案
使用下面的嵌套列表推导:
>>> 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']]
>>>
推荐阅读
- javascript - 我必须从数据库输出我的数据,还必须从表单中复制所有输入以将它们发送给我自己,包括实时乘法 weight*pcs
- import - 更改导入参数功能模块abap的值
- maven - 如何使用 p2-maven-plugin 包含到本地 p2-site 非 JAR 文件?
- ios - Flutter 无法构建 IOS 存档
- c# - Blazor 级联组件防止 StateHasChanged
- relationship - 使用 DirectQuery 在 PowerBI 中转换表列名称会删除该表的所有关系
- java - 根据登录用户和共享模式在运行时更改数据库模式
- python - 我正在尝试更新 tkinter 中的场景,我该怎么做?
- java - LinkedList 新的反向算法
- doctrine-orm - 如何选择在多对多关系中同时具有这两个项目的行