是否可以在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]
答案 0 :(得分:0)
使用zip
:
listString = ['a','b','c','d']
listInt = [1,2,3,4]
list(zip(listString, listInt))
# [('a', 1), ('b', 2), ('c', 3), ('d', 4)]
对于展平版本, itertools.chain
或嵌套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]