Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The pythonic way to generate pairs

I want something like code below, but "pythonic" style or using standard library:

def combinations(a,b):     for i in a:         for j in b:              yield(i,j) 
like image 770
Dima Avatar asked Jun 27 '11 21:06

Dima


People also ask

How do you create a pair in Python?

Care has to be taken while pairing the last element with the first one to form a cyclic pair. zip function can be used to extract pairs over the list and slicing can be used to successively pair the current element with the next one for the efficient pairing.

What is pair () in Python?

Pairs in Python. Page 1. Pairs in Python. To enable us to implement the concrete level of our data abstraction, Python provides a compound structure called a tuple, which can be constructed by separating values by commas. Although not strictly required, parentheses almost always surround tuples.

How do you connect pairs to a list in Python?

To join pairs of list elements in Python: Use list slicing with steps to get every second element starting at index 0 and 1 . Use the zip() function to iterate over the two lists. Use the addition operator (+) to join the list items.

Is there a pair in Python?

A Python dictionary is a collection of key-value pairs where each key is associated with a value. A value in the key-value pair can be a number, a string, a list, a tuple, or even another dictionary. In fact, you can use a value of any valid type in Python as the value in the key-value pair.


2 Answers

These are not really "combinations" in the sense of combinatorics, these are rather elements from the cartesian product of a and b. The function in the standard library to generate these pairs is itertools.product():

for i, j in itertools.product(a, b):     # whatever 
like image 131
Sven Marnach Avatar answered Oct 05 '22 18:10

Sven Marnach


As @Sven said, your code is attempting to get all ordered pairs of elements of the lists a and b. In this case itertools.product(a,b) is what you want. If instead you actually want "combinations", which are all unordered pairs of distinct elements of the list a, then you want itertools.combinations(a,2).

>>> for pair in itertools.combinations([1,2,3,4],2): ...    print pair ... (1, 2) (1, 3) (1, 4) (2, 3) (2, 4) (3, 4) 
like image 32
Rob Avatar answered Oct 05 '22 19:10

Rob