Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/python-2.7/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 2.7 Python:如何在一个列表中找到元素的索引,以及在另一个列表中找到它们对应的值_Python 2.7 - Fatal编程技术网

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

Python 2.7 Python:如何在一个列表中找到元素的索引,以及在另一个列表中找到它们对应的值,python-2.7,Python 2.7,我需要一点指导来完成这项任务。给定两个长度相同的不同列表,我想在一个列表(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 expectati

我需要一点指导来完成这项任务。给定两个长度相同的不同列表,我想在一个列表(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
A=[2,4,3]
B=[1,1,0]
对于b中的b:
索引_1=B.索引(B)
打印b,“”,索引_1
##__以下输出符合我的预期:
#    1  0
#    1  0
#    0  2
##___以下是我问题第二部分的代码:
_索引的值__1_b=A.index(索引_1)
打印索引_1,“,索引_1的值_\u b
##--以下是我的预期产出,但我没有得到这些:
#    0  2
#    0  4
#    2  3
感谢您的帮助。

A.index(index_1)
返回列表
A
index_1
的索引,而不是
A.index(index_1)
的第个值。您应该在索引
索引_1
处检索值:

 value_of_index_1_b = A[index_1]
那么你应该得到:

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

将zip函数与enumerate一起使用

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

既然您已经开始学习python语言的编程和编码,我强烈建议您切换到python 3,对python 2的支持将在明年年底结束。
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