在Python中添加包含字符串和整数值的列表

2024-05-19 20:27:29 发布

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

在Python中是否可以添加两个具有不同值类型的列表?还是有别的办法?例如:

listString = ['a','b','c','d']
listInt = [1,2,3,4]

我想将这些组合起来,以便输出字符串为: finalString = [('a',1),('b',2),('c',3),('d',4)]finalString = ['a',1,'b',2,'c',3,'d',4]


Tags: 字符串类型列表办法finalstringliststringlistint
1条回答
网友
1楼 · 发布于 2024-05-19 20:27:29

使用^{}

listString = ['a','b','c','d']
listInt = [1,2,3,4]

list(zip(listString, listInt))
# [('a', 1), ('b', 2), ('c', 3), ('d', 4)]

对于展平版本,^{}或嵌套的list comprehension

from itertools import chain
list(chain(*zip(listString, listInt)))
# ['a', 1, 'b', 2, 'c', 3, 'd', 4]

[x for pair in zip(listString, listInt) for x in pair]
# ['a', 1, 'b', 2, 'c', 3, 'd', 4]

相关问题 更多 >