简体   繁体   English

如何在Python中以元素方式连接列表?

[英]How to join lists element-wise in Python?

l1 = [4, 6, 8]
l2 = [a, b, c]

result = [(4,a),(6,b),(8,c)] 结果= [(4,a),(6,b),(8,c)]

How do I do that? 我怎么做?

The zip standard function does this for you: zip标准功能为您完成此操作:

>>> l1 = [4, 6, 8]
>>> l2 = ["a", "b", "c"]
>>> zip(l1, l2)
[(4, 'a'), (6, 'b'), (8, 'c')]

If you're using Python 3.x, then zip returns a generator and you can convert it to a list using the list() constructor: 如果您使用的是Python 3.x,那么zip返回一个生成器,您可以使用list()构造函数将其转换为列表:

>>> list(zip(l1, l2))
[(4, 'a'), (6, 'b'), (8, 'c')]

Use zip . 使用zip

l1 = [1, 2, 3]
l2 = [4, 5, 6]
>>> zip(l1, l2)
[(1, 4), (2, 5), (3, 6)]

Note that if your lists are of different lengths, the result will be truncated to the length of the shortest input. 请注意,如果列表的长度不同,则结果将被截断为最短输入的长度。

>>> print zip([1, 2, 3],[4, 5, 6, 7])
[(1, 4), (2, 5), (3, 6)]

You can also use zip with more than two lists: 您还可以使用带有两个以上列表的zip:

>>> zip([1, 2, 3], [4, 5, 6], [7, 8, 9])
[(1, 4, 7), (2, 5, 8), (3, 6, 9)]

If you have a list of lists, you can call zip using an asterisk: 如果您有列表列表,可以使用星号调用zip

>>> l = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
>>> zip(*l)
[(1, 4, 7), (2, 5, 8), (3, 6, 9)]
>>> l1 = [4, 6, 8]; l2 = ['a', 'b', 'c']
>>> zip(l1, l2)
[(4, 'a'), (6, 'b'), (8, 'c')]

If the lists are the same length, or if you want the length of the list to be the length of the shorter list, then use zip, as other people have pointed out. 如果列表的长度相同,或者您希望列表的长度是较短列表的长度,那么请使用zip,就像其他人指出的那样。

If the lists are different lengths, then you can use map with a transformation function of None : 如果列表的长度不同,则可以使用带None变换函数的map

>>> l1 = [1, 2, 3, 4, 5]
>>> l2 = [9, 8, 7]
>>> map(None, l1, l2)
[(1, 9), (2, 8), (3, 7), (4, None), (5, None)]

Note that the 'extra' values get paired with None . 请注意,'extra'值与None配对。

It's also worth noting that both zip and map can be used with any number of iterables: 值得注意的是, zipmap都可以与任意数量的iterables一起使用:

>>> zip('abc', 'def', 'ghi')
[('a', 'd', 'g'), ('b', 'e', 'h'), ('c', 'f', 'i')]
>>> map(None, 'abc', 'def', 'gh')
[('a', 'd', 'g'), ('b', 'e', 'h'), ('c', 'f', None)]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM