Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using a Python list comprehension a bit like a zip

Ok, so I'm really bad at writing Python list comprehensions with more than one "for," but I want to get better at it. I want to know for sure whether or not the line

>>> [S[j]+str(i) for i in range(1,11) for j in range(3) for S in "ABCD"]

can be amended to return something like ["A1","B1","C1","D1","A2","B2","C2","D2"...(etc.)]

and if not, if there is a list comprehension that can return the same list, namely, a list of strings of all of the combinations of "ABCD" and the numbers from 1 to 10.

like image 504
magnetar Avatar asked Dec 25 '22 18:12

magnetar


1 Answers

You have too many loops there. You don't need j at all.

This does the trick:

[S+str(i) for i in range(1,11) for S in "ABCD"]
like image 137
Daniel Roseman Avatar answered Dec 28 '22 08:12

Daniel Roseman