0

I try the code below, is there a efficent way to do this?

c = []
l = [['A1','A2'], ['B1','B2'],  ['C1','C2'] ]

for i in range(0, len(l) - 1):
    for j in range(i+1, len(l)): 
        c.append(sorted([l[i][0],l[i][1],l[j][0]]))
        c.append(sorted([l[i][0],l[i][1],l[j][1]]))
        c.append(sorted([l[i][0],l[j][0],l[j][1]]))
        c.append(sorted([l[i][1],l[j][0],l[j][1]]))

print(c)

Out put:

[['A1', 'A2', 'B1'], ['A1', 'A2', 'B2'], ['A1', 'B1', 'B2'],
['A2', 'B1', 'B2'], ['A1', 'A2', 'C1'], ['A1', 'A2', 'C2'], 
['A1', 'C1', 'C2'], ['A2', 'C1', 'C2'], ['B1', 'B2', 'C1'], 
['B1', 'B2', 'C2'], ['B1', 'C1', 'C2'], ['B2', 'C1', 'C2']
4
  • Try list(itertools.combinations(['A1', 'A2', 'B1', 'B2', 'C1', 'C2'], 3)) Commented Oct 18, 2016 at 7:05
  • @poke doesn't that produce a different result? Commented Oct 18, 2016 at 7:07
  • @vaultah You’re right. And now I’m confused. Nevermind me then. Commented Oct 18, 2016 at 7:12
  • It seems that way combinate 'A2', 'B2', 'C2', we need 2 items of the 3 items in one list Commented Oct 18, 2016 at 7:12

2 Answers 2

2

Try this:

# group every 2 lists in list l
ll = list(itertools.combinations(l, 2))

# generate all combinations of 3 elements out from each 2 lists
c = [list(itertools.combinations(a + b, 3)) for (a, b) in ll]

# concate all elements
c = sum(c, [])
Sign up to request clarification or add additional context in comments.

2 Comments

Also you need to list(map(list, c)) to have list of list objects as OP's output.
Since the OP asks about efficiency, c = sum(c, []) is probably not ideal (O(n^2)). A nested comprehension is more performant: c = [x for l in c for x in l]. (stackoverflow.com/questions/952914/…)
1

Or in one line

from itertools import product

c = [[k] + i for i, j in product(l, l) if j!=i for k in j]  

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.