Reputation: 33
I have a list and I want all possible combinations of items of a list.
from itertools import combinations
l = [1,2,3]
for i in combinations(l,2):
print(i) // (1, 2) (1,3) (2,3)
I want the same output but without using the itertools. I tried:
l = [1,2,3]
for i in l:
for j in l:
print((i,j)) // (1, 1), (1, 2), (1, 3), (2, 1), (2, 2), (2, 3), (3, 1), (3, 2), (3, 3)
How can I get the same output without using itertools?
Upvotes: 0
Views: 244
Reputation:
You can do this in a one liner just for efficiency:
l = [1, 2, 3]
([print(i, j) for i in l for j in l])
Upvotes: 0
Reputation: 23484
You can find sample implementation of itertools.combinations
in docs:
Roughly equivalent to:
def combinations(iterable, r): # combinations('ABCD', 2) --> AB AC AD BC BD CD # combinations(range(4), 3) --> 012 013 023 123 pool = tuple(iterable) n = len(pool) if r > n: return indices = list(range(r)) yield tuple(pool[i] for i in indices) while True: for i in reversed(range(r)): if indices[i] != i + n - r: break else: return indices[i] += 1 for j in range(i+1, r): indices[j] = indices[j-1] + 1 yield tuple(pool[i] for i in indices)
Upvotes: 1
Reputation: 163
Maybe try this
l = [1, 2, 3]
for i in l:
for j in l:
if(j <= i):
continue
else:
print(i, j)
Upvotes: 1