python-2.7 - 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
谢谢你的帮助。
解决方案
A.index(index_1)
返回列表中的索引,而不是 的第 th 值。您应该改为检索索引处的值:index_1
A
A.index(index_1)
A
index_1
value_of_index_1_b = A[index_1]
那么你应该得到:
# 0 <---> 2
# 0 <---> 2 (not 4)
# 2 <---> 3
推荐阅读
- php - 插入空数据Mysql的最佳方法是什么
- php - Laravel 多态关系同时存储数据
- c++11 - c ++随机设置种子失败
- react-router-v4 - 将 withTheme 包装的组件传递给 Route 时为什么会发出警告?
- mysql - 在配置文件中添加 lower_case_table_names=2 后,mysql 8.0 将启动
- python - 无法卸载“numpy”。它是一个 distutils 安装的项目,因此我们无法准确确定哪些文件属于
- java - git api 在 Java 上进行操作
- angular - Angular 7从组件导航到另一个
- c# - 如何在 web api swagger 的标头中将用户名作为 base 64 编码格式传递?
- spring-boot - Thymeleaf th:field 不绑定输入文本的值