python - Identify index of all elements in a list comparing with another list
问题描述
For instance I have a list A
:
A = [100, 200, 300, 200, 400, 500, 600, 400, 700, 200, 500, 800]
And I have list B
:
B = [100, 200, 200, 500, 600, 200, 500]
I need to identify the index of elements in B
with comparison to A
I have tried:
list_index = [A.index(i) for i in B]
It returns:
[0, 1, 1, 5, 6, 1, 5]
But what I need is:
[0, 1, 3, 5, 6, 9, 10]
How can I solve it?
解决方案
You can iterate through the enumeration of A
to keep track of the indices and yield the values where they match:
A = [100,200,300,200,400,500,600,400,700,200,500,800]
B = [100,200,200,500,600,200,500]
def get_indices(A, B):
a_it = enumerate(A)
for n in B:
for i, an in a_it:
if n == an:
yield i
break
list(get_indices(A, B))
# [0, 1, 3, 5, 6, 9, 10]
This avoids using index()
multiple times.
推荐阅读
- python - 有没有办法告诉我whatsapp中的消息是否被标记(或回复)
- postgresql - pgAudit 未在 GCP Cloud SQL 中记录任何内容
- java - 如何访问 QueryDSL QuerydslBinderCustomizer 中的跨字段值?
- powershell - docx和pdf文件的AES加密/解密不起作用
- reactjs - oninvalid 属性未在 React js 中呈现
- python - 使用 pysimplegui,sg.InputText 不返回 int 而是返回范围的字符串
- css - Bootstrap 5 svg 图标不出现
- apache-kafka - KSQL - 使用联合模式将多个查询流式传输到单个主题
- server - 在 Hostinger 上托管。AWS 服务器设置
- json - Kotlin 密封接口序列化