同时遍历多个列表并捕获值的差异 [英] Simultaneously iterate over multiple list and capture difference in values

查看:66
本文介绍了同时遍历多个列表并捕获值的差异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑API返回四个列表作为输出.让我们将输出视为

Consider API returning four lists as output. Let's consider output as

a = [1,2,3,4]
b = [1,2,3,4]
c = [1,2,4,3]
d = [1,2,3,5]

现在,首先我们要比较这些列表是否相等.

Now, first we want to compare these lists are equal or not.

仅当元素和那里的索引匹配时,列表才相等. 例如,从上面的列表中,ab相等.但是ac不相等.

Lists are equal only if elements and there indexes matches. For example, from above lists, a and b are equal. But a and c are not equal.

如果列表不相等,则预期输出为:此列表中此索引处的此元素与其他元素不同.

If the lists are not equal, then output is expected as: this element at this index in this list is not same as other.

为了比较和得到两个列表的差异,我在下面编写了代码.

For comparing and getting differences of two lists, I have written below code.

for i in range(len(a)):
    if a[i] != c[i]:
        print "Expected value at ",i," is ",a[i]
        print "But got value ",c[i],"in second list"    

现在的问题是如何针对以上四个列表实现这一目标?

Now question is how to achieve this for all four above lists?

推荐答案

您可以使用

You may use zip to iterate over each list simultaneously and compare the value at each index. In the below example, I am comparing the value of list a with remaining lists.

a = [1,2,3,4]
b = [1,2,3,4]
c = [1,2,4,3]
d = [1,2,3,5]

for i, x in enumerate(zip(a, b, c, d)):
    print('--------- Index: {}'.format(i))
    base = x[0]
    for j, y in enumerate(x[1:], 2):
        if base!=y:
            print('{} not equal to {} : --> List {}'.format(base, y, j))

打印:

--------- Index: 0
--------- Index: 1
--------- Index: 2
3 not equal to 4 : --> List 3
--------- Index: 3
4 not equal to 3 : --> List 3
4 not equal to 5 : --> List 4

这篇关于同时遍历多个列表并捕获值的差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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