【问题标题】:How to compare the first tuple from one list of tuples with the first from another list, then the second with the second list, and so on?如何将一个元组列表中的第一个元组与另一个列表中的第一个元组进行比较,然后将第二个元组与第二个列表进行比较,依此类推?
【发布时间】:2019-11-14 18:22:18
【问题描述】:

我正在尝试比较两个由整数组成的元组列表,但我似乎无法成功。 list_a = [(1, 1), (2, 2), (3, 4), (4, 1)] list_b = [(1, 2), (2, 2), (3, 1), (4, 1)]

我正在尝试将第一个元组与另一个列表的第一个元组进行比较,然后将第二个元组与第二个元组进行比较,然后将第三个元组进行比较。

我尝试遍历两个列表和值,如下所示。

for w, x in list_a: 
    for y, z in list_b:
        if x == z:
            total += 1
            break
        else:
            total -= 1
            break

在第一个循环中,来自 value 的变量“w”和“x”将得到值:(1, 1)。然后 "y" 和 "z" 将得到 (1, 2) 并进行比较。到目前为止,一切都很好。 我的问题是“y”和“z”将循环通过list_b的第二个元组,而“w”和“x”将保留在list_a的第一个元组中

我希望这是可以理解的,对不起,我有很好的英语知识,但有时很难解释这种东西。

【问题讨论】:

    标签: python-3.x tuples iteration


    【解决方案1】:

    您应该将它们zip() 放在一起,这样您就可以在一个列表迭代中比较整个元组的值:

    list_a = [(1, 1), (2, 2), (3, 4), (4, 1)] 
    list_b = [(1, 2), (2, 2), (3, 1), (4, 1)]
    
    total = 0
    for (w, x), (y, z) in zip(list_a, list_b):
        # (w, x) are from list_a
        # (y, z) are from list_b
        if x == z:
            total += 1
        else:
            total -= 1
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-11-16
      • 2020-02-28
      • 2013-09-25
      • 1970-01-01
      • 1970-01-01
      • 2013-05-24
      • 2020-03-04
      相关资源
      最近更新 更多