首页 > 解决方案 > Python:如何在一个列表中查找元素的索引,以及它们在另一个列表中的对应值

问题描述

我需要一些指导来完成这项任务。给定两个具有相同长度的不同列表,我想在一个列表 (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

谢谢你的帮助。

标签: python-2.7

解决方案


A.index(index_1)返回列表中的索引,而不是 的第 th 值。您应该改为检索索引处的值:index_1AA.index(index_1)Aindex_1

 value_of_index_1_b = A[index_1]

那么你应该得到:

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

推荐阅读