How to join item lists in Python?

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

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

How to do it?

+3
source share
4 answers

Use zip.

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

Please note that if your lists have 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([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 zipwith an asterisk:

>>> l = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
>>> zip(*l)
[(1, 4, 7), (2, 5, 8), (3, 6, 9)]
+11
source

The standard function zipdoes this for you:

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

If you use Python 3.x, it zipreturns a generator, and you can convert it to a list using the constructor list():

>>> list(zip(l1, l2))
[(4, 'a'), (6, 'b'), (8, 'c')]
+12
source
>>> l1 = [4, 6, 8]; l2 = ['a', 'b', 'c']
>>> zip(l1, l2)
[(4, 'a'), (6, 'b'), (8, 'c')]
+1

, zip, .

If lists have different lengths, you can use mapwith the conversion function None:

>>> 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 "optional" values ​​are connected to None.

It is also worth noting that both zipand mapcan be used with any number of iterations:

>>> 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)]
0
source

Source: https://habr.com/ru/post/1725360/


All Articles