Pythonic方式比较两个列表并打印出差异 [英] Pythonic way to compare two lists and print out the differences

查看:103
本文介绍了Pythonic方式比较两个列表并打印出差异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个保证长度相同的列表。我想比较列表中的相应值(除了第一项),并打印出不匹配的值。我这样做的方式是这样

I have two lists which are guaranteed to be the same length. I want to compare the corresponding values in the list (except the first item) and print out the ones which dont match. The way I am doing it is like this

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)

Is there a better way to do this? (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 个第一项(相同的输出):

Easily extended to skip n first items (same output):

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方式比较两个列表并打印出差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆