将一个列表中的所有元素与另一个列表进行比较并确定它们的索引。

16
例如我有一个列表A
A = [100, 200, 300, 200, 400, 500, 600, 400, 700, 200, 500, 800]

我有一个列表 B:

B = [100, 200, 200, 500, 600, 200, 500]

我需要确定以A为基准,B中元素的索引。

我已尝试过:

list_index = [A.index(i) for i in B]

它返回:

[0, 1, 1, 5, 6, 1, 5]

但我需要的是:

[0, 1, 3, 5, 6, 9, 10]

我该如何解决这个问题?


1
需要编写更多的代码。您需要为每个值跟踪最新使用的索引,并对该值的下一个出现使用该索引之后的索引。 - Samwise
1
你的意思是 [0, 1, 3, 5, 6, 9, 10],也就是说只使用 A 中的每个元素一次吗?那么对于例如 [500, 200],你期望得到什么结果? - Nyps
@Nyps 对于 [500,200],它必须返回 [5,9]。 - narashimhaa Kannan
2
如果其中一个未被包含或顺序不正确怎么办?例如:x = [800, 200, 500]y = [200, 500, 900] - Mojtaba Hosseini
6个回答

15
您可以遍历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()


4
你可以创建一个名为indices的列表,并获取其第一个索引。然后迭代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]

4
您可以尝试像这样做。遍历两个列表,当它们相等时附加索引:
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]


3

以下是我会使用的内容:

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)

3
A = np.array([100,200,300,200,400,500,600,400,700,200,500,800])
B = [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]

1
我遍历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]

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接