我有两个保证长度相同的列表。我想比较列表中的相应值(第一项除外)并打印出不匹配的值。我的做法是这样的
i = len(list1)
if i == 1:
print 'Nothing to compare'
else:
for i in range(i):
if not (i == 0):
if list1[i] != list2[i]:
print list1[i]
print list2[i]
有没有更好的方法来做到这一点? (Python 2.x)
最佳答案
list1=[1,2,3,4]
list2=[1,5,3,4]
print [(i,j) for i,j in zip(list1,list2) if i!=j]
输出:
[(2, 5)]
编辑:轻松扩展以跳过第 n 个项目(相同的输出):
list1=[1,2,3,4]
list2=[2,5,3,4]
print [(i,j) for i,j in zip(list1,list2)[1:] if i!=j]
关于比较两个列表并打印出差异的 Pythonic 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2387981/