[英]How to find index of element of one list in another list which includes the same elements?
我正在尝试用 python 编写这个简单的任务(一个更大项目的一部分):
我有两个列表,其中第一个列表,假设A = [1, 2, 3, 4, 5, 6]
已排序,第二个列表,假设B = [3, 4, 1, 6, 2, 5]
没有排序。 我想要实现的是获取列表B
排序列表A
每个元素的索引值。 例如,当我搜索元素A[5] = 6
时,我想得到索引i = 3
的结果。 我以简单的方式实现如下:
for i in range(6):
for j in range(6):
if A[i] == B[j]:
index = j
我想想出一种方法,将它减少到只有一个循环,而不是这两个嵌套的for
循环。
如果您知道B
中的所有值都是唯一的,一种方法是创建一个字典,将B
的值映射到它们的索引。
b_dict = {}
for i, b in enumerate(B):
b_dict[b] = i
然后,循环A
并从b_dict
获取所有值。
a_indices = [b_dict[a] for a in A]
有了你的清单,我们得到
A: [1, 2, 3, 4, 5, 6]
B: [3, 4, 1, 6, 2, 5]
a_indices: [2, 4, 0, 1, 5, 3]
这个解决方案是 O(n) 而不是其他的 O(n^2),因此在大型列表上会快得多。
最简单的可能解决方案是,
A = [1, 2, 3, 4, 5, 6]
B = [3, 4, 1, 6, 2, 5]
x= [B.index(i) for i in A]
#To store the result in a dictionary to map value and corresponding index.
a=dict(zip(A,x))
您可以使用list.index()
方法来查找列表中特定元素的索引:
indices = {}
for elem in A:
indices[elem] = B.index(elem)
# {1: 2, 2: 4, 3: 0, 4: 1, 5: 5, 6: 3}
尝试这个:
for x in A:
index = B.index(x)
这里 index 是每次迭代的索引变量。
要保存在字典中:
indices = {}
for x in A:
indices[x] = B.index(x)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.