![](/img/trans.png)
[英]Identify distinct elements in a list and map it to a corresponding index in another list in python
[英]Identify index of all elements in a list comparing with another list
例如我有一个列表A
:
A = [100, 200, 300, 200, 400, 500, 600, 400, 700, 200, 500, 800]
我有清单B
:
B = [100, 200, 200, 500, 600, 200, 500]
我需要确定元素的索引B
与比较A
我努力了:
list_index = [A.index(i) for i in B]
它返回:
[0, 1, 1, 5, 6, 1, 5]
但我需要的是:
[0, 1, 3, 5, 6, 9, 10]
我该如何解决?
您可以遍历A
的枚举以跟踪索引并生成它们匹配的值:
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]
这避免了多次使用index()
。
你可以尝试这样的事情。 移动两个列表并在它们相等时附加索引:
A = [100,200,300,200,400,500,600,400,700,200,500,800]
B = [100,200,200,500,600,200,500]
i, j = 0, 0
list_index = []
while j < len(B):
if B[j] == A[i]:
list_index.append(i)
j += 1
i += 1
print(list_index)
输出:
[0, 1, 3, 5, 6, 9, 10]
这是我将使用的:
A=[100,200,300,200,400,500,600,400,700,200,500,800]
B=[100,200,200,500,600,200,500]
list_index = []
removedElements = 0
for i in B:
indexInA = A.index(i)
A.pop(indexInA)
list_index.append(indexInA+removedElements)
removedElements+=1
print(list_index)
您可以创建一个名为索引的列表,并将第一个索引放入其中。 然后迭代B
其余项目,然后从indices
列表中的最后一个索引中取出A
的切片并获取该项目的索引,将其添加到最后一个索引 + 1,然后将其附加回indices
列表。
indices = [A.index(B[0])]
for i,v in enumerate(B[1:]):
indices.append(A[indices[-1]+1:].index(v)+indices[-1]+1)
#indices: [0, 1, 3, 5, 6, 9, 10]
A = np.array([100,200,300,200,400,500,600,400,700,200,500,800])
B = np.array([100, 200, 200, 500, 600, 200, 500])
idx = np.arange(len(A))
indices = {i: idx[A == i].tolist() for i in set(B)}
[indices[i].pop(0) for i in B]
我遍历 B 并将检查的索引设置为 A 中的无。因此代码将更改 A。
A = [100, 200, 300, 200, 400, 500, 600, 400, 700, 200, 500, 800]
B = [100, 200, 200, 500, 600, 200, 500]
res = []
for i in B:
res.append(A.index(i))
A[A.index(i)] = None
print(res)
输出:
[0, 1, 3, 5, 6, 9, 10]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.