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)
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.
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.
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.
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.
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
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With