简体   繁体   中英

How to get all pair of items from the list without using the itertools import combination

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?

Maybe try this

l = [1, 2, 3]
for i in l:
    for j in l:
        if(j <= i):
            continue
        else:
            print(i, j)

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) 

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])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM