Python 检查2个列表是否具有相同的值或值、索引
我有这两张单子Python 检查2个列表是否具有相同的值或值、索引,python,list,Python,List,我有这两张单子 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
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]
或者有没有更简单的方法?
谢谢大家! 两次看到打印输出的原因是
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())
您的逻辑在查找号码时出错:
for x in a:
for y in b:
if x == y:
if (a.index(x) == b.index(y)):
索引
查找第一次出现的值。你想要的输出取决于你知道你有哪个索引。相反,要同时跟踪值和索引:
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
哦,我明白了,我不知道。索引是否只返回值的第一次出现。因此,谢谢大家!这解决了我的问题:)