检查两个列表是否具有相同的值或值,索引

时间:2020-08-06 22:50:51

标签: python list

我有这2个列表

a = [3,9,1,4,5]
b = [7,2,1,0,1]

我试图根据某种条件(同一值或相同的索引和2列表中的值)打印一行,并且输出应为

"Same Value(for duplicate number)"
"Same Value + Index(for duplicate number and same index)"

我尝试使用迭代,如果这样的话

for x in a:
    for y in b:
        if x == y:
            if (a.index(x) == b.index(y)):
                print("Same Value + Index")
            else:
                print("Same Value")

但是输出以某种方式显示了这一点:

Same Value + Index
Same Value + Index
[Finished in 0.4s]

或者有没有更简单的方法? 谢谢!

2 个答案:

答案 0 :(得分:2)

您查找数字的逻辑有误:

for x in a:
    for y in b:
        if x == y:
            if (a.index(x) == b.index(y)):

index查找该值的 first 出现。所需的输出取决于知道您拥有的哪个索引。相反,请同时跟踪值和索引:

for x_idx, x in enumerate(a):
    for y_idx, y in enumerate(b):
        if x == y:
            if x_idx == y_idx:   # This uses the current index

答案 1 :(得分:1)

您两次看到打印输出的原因是list.index返回列表中某个值的第一个出现的索引,而不是“当前”值的索引。因此,当您的第二个列表位于索引4且第一个列表位于索引2时,b.index(1)返回2,而不是4,然后发生第二个打印输出。

您应该跟踪当前位置:

for i, x in enumerate(a):
    for j, y in enumerate(b):
        if x == y:
            if i == j:
                print("Same Value + Index")
            else:
                print("Same Value")

如果您关心的是与每个条件匹配的条目数:

both_match = len(set(enumerate(a)) & set(enumerate(b)))

获得相同数量的“任何匹配项”都比较棘手。您可以使用collections.Counter来获得正确的数字:

ca = Counter(a)
cb = Counter(b)
value_match = sum(ca[k] * cb[k] for k in ca.keys() & cb.keys())