python: create list of tuples from lists [duplicate]
I have two lists:
x = ['1', '2', '3']
y = ['a', 'b', 'c']
and I need to create a list of tuples from these lists, as follows:
z = [('1','a'), ('2','b'), ('3','c')]
I tried doing it like this:
z = [ (a,b) for a in x for b in y ]
but resulted in:
[('1', '1'), ('1', '2'), ('1', '3'), ('2', '1'), ('2', '2'), ('2', '3'), ('3', '1'), ('3', '2'), ('3', '3')]
i.e. a list of tuples of every element in x with every element in y... what is the right approach to do what I wanted to do? thank you...
EDIT: The other开发者_开发技巧 two duplicates mentioned before the edit is my fault, indented it in another for-loop by mistake...
Use the builtin function zip()
:
In Python 3:
z = list(zip(x,y))
In Python 2:
z = zip(x,y)
You're looking for the zip builtin function. From the docs:
>>> x = [1, 2, 3]
>>> y = [4, 5, 6]
>>> zipped = zip(x, y)
>>> zipped
[(1, 4), (2, 5), (3, 6)]
You're after the zip function.
Taken directly from the question: How to merge lists into a list of tuples in Python?
>>> list_a = [1, 2, 3, 4]
>>> list_b = [5, 6, 7, 8]
>>> zip(list_a,list_b)
[(1, 5), (2, 6), (3, 7), (4, 8)]
精彩评论