Creating pairs from a python list

I am trying to create a bunch of pairs from a list in python --- I figured out a way to do this using for loops:

keys = range(10)
keypairs = list()
for i in range(len(keys)):
        for j in range(i+1, len(keys)):
            keypairs = keypairs + [(keys[i], keys[j])]

Is there a "python style" way? My method does not seem very elegant ...

+4
source share
3 answers

You want two ranges of the loop, one from 0 to n, and an inner one from each i of the first range from + 1 to n, using the comp list:

n = 10
pairs = [(i, j) for i in range(n) for j in range(i+1, n)]
from pprint import pprint as pp
pp(pairs,compact=True)


[(0, 1), (0, 2), (0, 3), (0, 4), (0, 5), (0, 6), (0, 7), (0, 8), (0, 9), (1, 2),
 (1, 3), (1, 4), (1, 5), (1, 6), (1, 7), (1, 8), (1, 9), (2, 3), (2, 4), (2, 5),
 (2, 6), (2, 7), (2, 8), (2, 9), (3, 4), (3, 5), (3, 6), (3, 7), (3, 8), (3, 9),
 (4, 5), (4, 6), (4, 7), (4, 8), (4, 9), (5, 6), (5, 7), (5, 8), (5, 9), (6, 7),
 (6, 8), (6, 9), (7, 8), (7, 9), (8, 9)]

What exactly matches your result.

+2
source

You want to check the list comprehension:

sorted([(i, j) for j in range(10) for i in range(10) if j > i])
+1
source

itertools. combinations_with_replacement combinations .

:

import itertools
list(itertools.combinations(keys, 2))

EDITED: , , combinations, combinations_with_replacements.

+1

Source: https://habr.com/ru/post/1615792/


All Articles