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

时间:2018-01-15 04:28:41

标签: python list

是否可以在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]

1 个答案:

答案 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]