代码之家  ›  专栏  ›  技术社区  ›  Vondoe79

Python:如何在一个列表中找到元素的索引,在另一个列表中找到它们对应的值

  •  0
  • Vondoe79  · 技术社区  · 6 年前

    我需要一点指导来完成这项任务。给定两个长度相同的不同列表,我想在一个列表(B)中找到元素的索引,在另一个列表(A)中找到它们对应的值。下面是我写的一段代码,但第二部分并不像我预期的那样工作。

    A = [2,4,3]
    B = [1,1,0]
    for b in B:
        index_1 = B.index(b)
        print b, "<--->", index_1
    
        ##__the following outputs are correct by my expectation:
         #    1 <---> 0
         #    1 <---> 0
         #    0 <---> 2
    
        ##___Below code is for the second part of my question:
        value_of_index_1_b = A.index(index_1)
        print index_1, "<--->", value_of_index_1_b
    
     ##-- And, the following was my expected outputs, but I'm not getting these:
           #    0 <---> 2
           #    0 <---> 4
           #    2 <---> 3
    

    2 回复  |  直到 6 年前
        1
  •  0
  •   Khalil Al Hooti    6 年前

    将zip函数与枚举一起使用

    for i, (b, a) in enumerate(zip(B, A)):
       index_1 = i
       print b , "<--->", index_1
    

    i

    下面是一个已解决的示例

    A = [2,4,3]
    B = [1,1,0]
    
    for i, (a, b) in enumerate(zip(A,B)):
    
        print(i, a, b, A[i]==a, B[i]==b)
    
    0 2 1 True True
    1 4 1 True True
    2 3 0 True True
    
        2
  •  0
  •   ForceBru    6 年前

    A.index(index_1) 返回 属于 index_1 A ,而不是 的th值 A 检索 索引处的值 索引\u 1

     value_of_index_1_b = A[index_1]
    

    那么你应该得到:

    #    0 <---> 2
    #    0 <---> 2 (not 4)
    #    2 <---> 3