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

橙三吉。 提交于 2019-12-03 09:44:09

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
    
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!