Possible Duplicate:
How to generate all permutations of a list in Python
I want to find all the permutations of a the elements in a list. but then with some conditions imposed.. umm.. Probably an example will help me explain better.
I have four lists
["1"],["0"],["a","b","c],["d","e","f"]
Now I want to have the permutations in following way:
"10ad" ,"10bd","10cd","10ae", "10be"
,"10bf"..
and so on..
So basically every element (with every element)?? Now I know the very naive way to do this. But what is the pythonic way to do this? if there is any?? Any suggestions
Thanks
-
If the order matters, please explain the ordering you want better; I would have expected "10ce" to come after "10be".Scott Hunter– Scott Hunter04/06/2012 03:00:57Commented Apr 6, 2012 at 3:00
-
@ScottHunter: the order doesnt matter actually :)frazman– frazman04/06/2012 03:12:04Commented Apr 6, 2012 at 3:12
1 Answer 1
I think you want to use the itertools
module, which is part of the standard Python distribution.
For example:
import itertools
a = ["1"]
b = ["0"]
c = ["a","b","c"]
d = ["d","e","f"]
for item in itertools.product(a, b, c, d):
print(item)
Edit: To be clear, the itertools.product
function provides all combinations for all items in the inputted lists, not permutations. But based on OP's wording, I think this is what he/she actually wants.
-
1Great answer. This returns tuples, so slight adjustment to exactly match the question would be something like:
for item in itertools.product(a,b,c,d): print '%s%s%s'%item
Collin Green– Collin Green04/06/2012 03:05:39Commented Apr 6, 2012 at 3:05 -
2Or alternatively, if you want a list of strings, you can just
''.join(item)
Casey Kuball– Casey Kuball04/06/2012 04:05:03Commented Apr 6, 2012 at 4:05