Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python all possible pairs of 2 list elements, and getting the index of that pair

People also ask

How do you generate all possible combinations of two lists in Python?

The unique combination of two lists in Python can be formed by pairing each element of the first list with the elements of the second list. Method 1 : Using permutation() of itertools package and zip() function. Approach : Import itertools package and initialize list_1 and list_2.

How do you find the pair of elements in a list in Python?

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.

How do you find the pairwise combination?

TLDR; The formula is n(n-1)/2 where n is the number of items in the set.

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.


And to complete the answer and stay in the example:

import itertools  

a = [1, 2, 3]
b = [4, 5, 6]
c = list(itertools.product(a, b))

idx = c.index((1,4))

But this will be the zero-based list index, so 0 instead of 1.


One way to do this:

  1. Find the first element of the pair your are looking for in the first list:

    p = (1, 4)
    i = a.index(p[0])
    
  2. Find the second element of the pair your are looking for in the second list:

    j = b.index(p[1])
    
  3. Compute the index in the product list:

    k = i * len(b) + j