440,034 Members | 2,000 Online
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 440,034 IT Pros & Developers. It's quick & easy.

# List Combinations

 P: n/a I have a list that looks like this: [['3'], ['9', '1'], ['5'], ['4'], ['2', '5', '8']] how can I get all the combinations thereof that looks like as follows: 3,9,5,4,2 3,1,5,4,2 3,9,5,4,5 3,1,5,4,5 etc. Thank You, Gerdus Mar 12 '08 #1
4 Replies

 P: n/a On Mar 12, 10:18 am, Gerdus van Zyl

 P: n/a On Mar 12, 10:18*am, Gerdus van Zyl >from itertools import productfor c in product(['3'], ['9', '1'], ['5'], ['4'], ['2', '5', '8']): print c ... ('3', '9', '5', '4', '2') ('3', '9', '5', '4', '5') ('3', '9', '5', '4', '8') ('3', '1', '5', '4', '2') ('3', '1', '5', '4', '5') ('3', '1', '5', '4', '8') If you can't wait, look at http://docs.python.org/dev/library/itertools.html where equivalent code is given. Mark Mar 12 '08 #3

 P: n/a Gerdus van Zyl wrote: I have a list that looks like this: [['3'], ['9', '1'], ['5'], ['4'], ['2', '5', '8']] how can I get all the combinations thereof that looks like as follows: 3,9,5,4,2 3,1,5,4,2 3,9,5,4,5 3,1,5,4,5 etc. Thank You, Gerdus What they said, or, if you want to see it done: def combi (s): if s: for a in s[0]: for b in combi (s[1:]): yield [a] + b else: yield [] for y in combi ([['3'], ['9', '1'], ['5'], ['4'], ['2', '5', '8']]): print y Mar 12 '08 #4

 P: n/a On Mar 12, 3:38*pm, "Reedick, Andrew" = 0: if i == n: yield tuple(vals) i -= 1 else: for vals[i] in iters[i]: i += 1 break else: iters[i] = iter(sequences[i]) i -= 1 It's neither recursive nor a hack, I haven't tried to measure it against other approaches (obviously it wouldn't beat the eval(...) hack). I haven't optimised it for readability (by others) either :) -- Arnaud Mar 12 '08 #5

### This discussion thread is closed

Replies have been disabled for this discussion.