Python - 列出连接

时间:2015-01-05 23:42:10

标签: python list

我有两个列表,我想创建一个包含其数据的列表。

ls1 = ["1","2","3","4"]

ls2 = ["4","3","2","1"]

我正在寻找的答案就是这种形式......

ls3 = ["1-4","2-3","3-2","4-1"]

有可能实现这一目标吗?注意数字之间的减号。

3 个答案:

答案 0 :(得分:7)

>>> ls3 = ['-'.join(x) for x in zip(ls1, ls2)]
['1-4', '2-3', '3-2', '4-1']

答案 1 :(得分:2)

所以@ esthete的答案是正确的。我只想补充说明。

>>> ls3 = ['-'.join(x) for x in zip(ls1, ls2)]
['1-4', '2-3', '3-2', '4-1']

[someaction(x) for x in somelist]将返回一个列表,其中每个元素someaction()都在x中的相应somelist上执行。这称为列表理解

在这种情况下,somelistzip(ls1,ls2),会创建[(ls1[0], ls2[0]), (ls1[1], ls2[1]), ...]

所以zip(ls1,ls2)返回[('1', '4'), ('2', '3'), ('3', '2'), ('4', '1')]

someaction()'-'.join()它的作用是它需要一个可迭代的字符串序列,并将它们与字符串'-'连接在一起。因此,您可以' to '.join(x)完成['1 to 4', '2 to 3', ...]

答案 2 :(得分:2)

>>> [ "{}-{}".format(ls1[x],ls2[x]) for x in range(len(ls1))]
['1-4', '2-3', '3-2', '4-1']

使用map:

>>> map("{}-{}".format,ls1,ls2)
['1-4', '2-3', '3-2', '4-1']

使用itertools.strmap:

>>> list(itertools.starmap("{}-{}".format,zip(ls1,ls2)))
['1-4', '2-3', '3-2', '4-1']