How to get tuples from lists using list comprehension in python

I have two lists and you want to combine them into one tuples list. I want to do this with list comprehension , I can make it work with map . but it would be nice to know how it would look here. code here

 >>> lst = [1,2,3,4,5] >>> lst2 = [6,7,8,9,10] >>> tup = map(None,lst,lst2) # works fine >>> tup [(1, 6), (2, 7), (3, 8), (4, 9), (5, 10)] >>> l3 = [lst, lst2] >>> l3 [[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]] >>> zip(*l3) # works fine [(1, 6), (2, 7), (3, 8), (4, 9), (5, 10)] >>> [(i,j) for i in lst and for j in lst2] # does not work File "<stdin>", line 1 [(i,j) for i in lst and for j in lst2] ^ SyntaxError: invalid syntax >>> 

I wrote comments where it works and where not. How can I link two for-loop in list comprehension

+8
python list tuples list-comprehension
source share
2 answers

Think about how to think of a list as loops. How can you write 2 non-nested loops?

You can do this with an understanding of several countries:

 [(x, lst2[i]) for i, x in enumerate(lst)] 

or

 [(lst[i], lst2[i]) for i in xrange(len(lst))] 

But actually it is better to use zip .

+13
source share

The way to comprehend the list is stupid because it just wraps the comprehension of the nothing-to-nothing list around zip :

 [(i,j) for i, j in zip(lst, lst2)] 

Just use zip for what it is needed. It makes no sense to force yourself to use lists when they do nothing.

Edit: if your question is “How can I get two for loops in the same list comprehension”, you should ask about it. Answer: "You cannot get two pairs of PARALLEL for in one understanding of the list." Each time you put two for clauses into a list comprehension, they will be nested. This is a list comprehension like this:

 [... for a in list1 for b in list2] 

Works like two nested for loops:

 for a in list1: for b in list2: ... 

You cannot write a list comprehension that does the following:

 for a in list1: ... for b in list2: ... 

., and you don’t need it, because instead you are executing the zip function.

(You can fake it with a solution like @Roman Pekar, but actually it does not do two for loops, it just does it and uses the values ​​from it to get to another list.)

+5
source share

All Articles