Created
September 6, 2013 07:35
-
-
Save gideondsouza/6460685 to your computer and use it in GitHub Desktop.
Python Comprehensions 3
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
>>> | |
>>> L = [1,2,3,4,5] #define a list 1 to 5 | |
>>> [(x,y) for x in L for y in L] # we have two fors running over the list | |
#this gives all the 25 non-unique combinations | |
[(1, 1), (1, 2), (1, 3), (1, 4), (1, 5), (2, 1), (2, 2), (2, 3), (2, 4), (2, 5), | |
(3, 1), (3, 2), (3, 3), (3, 4), (3, 5), (4, 1), (4, 2), (4, 3), (4, 4), (4, 5), | |
(5, 1), (5, 2), (5, 3), (5, 4), (5, 5)] | |
#need unque combinations. No problem! Add an if in the end. | |
>>> [(x,y) for x in L for y in L if x!=y] | |
[(1, 2), (1, 3), (1, 4), (1, 5), (2, 1), (2, 3), (2, 4), (2, 5), (3, 1), (3, 2), | |
(3, 4), (3, 5), (4, 1), (4, 2), (4, 3), (4, 5), (5, 1), (5, 2), (5, 3), (5, 4)] | |
>>> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment