【问题标题】:Comparing two lists element-wise in python [duplicate]在python中比较两个列表元素[重复]
【发布时间】:2019-09-22 23:04:47
【问题描述】:

我有两个列表

first= (1,2,3,4,5,6)
last=(6,5,4,3,2,1)

我只需要比较相应的值。我使用了下面的代码并获得了 36 个结果,因为第一个元素与最后一个列表的所有六个元素进行了比较。

for x in first:
    for y in last:
        if x>y:
            print("first is greater then L2",y)
        elif x==y:
            print("equal")
        else:
            print("first is less then L2",y)

irst= (1,2,3,4,5,6)
last=(6,5,4,3,2,1)
for x in first:
    for y in last:
        if x>y:
            print("first is greater then L2",y)
        elif x==y:
            print("equal")
        else:
            print("first is less then L2",y)

输出:

L1 is less then L2 6
L1 is less then L2 5
L1 is less then L2 4
L1 is less then L2 3
L1 is less then L2 2
go dada
L1 is less then L2 6
L1 is less then L2 5
L1 is less then L2 4
L1 is less then L2 3
go dada
L1 is greater then L2 1
L1 is less then L2 6
L1 is less then L2 5
L1 is less then L2 4
go dada
L1 is greater then L2 2
L1 is greater then L2 1
L1 is less then L2 6
L1 is less then L2 5
go dada
L1 is greater then L2 3
L1 is greater then L2 2
L1 is greater then L2 1
L1 is less then L2 6
go dada
L1 is greater then L2 4
L1 is greater then L2 3
L1 is greater then L2 2
L1 is greater then L2 1
go dada
L1 is greater then L2 5
L1 is greater then L2 4
L1 is greater then L2 3
L1 is greater then L2 2
L1 is greater then L2 1
y

我只需要比较相应元素的结果。这意味着应该只有六个输出。

【问题讨论】:

  • (1,2,3,4,5,6) 不是一个列表。它是一个元组。
  • 这就是 R 击败 python 的原因。 x = c(1, 2, 3) x[x %in% c(2, 3)] = (2, 3)

标签: python python-3.x


【解决方案1】:

firstlast 是元组,而不是列表(列表元素在方括号内,如 [1,2,3])。

您可以使用zip(first,last) 从两个元组创建一个对列表:

[(1, 6), (2, 5), (3, 4), (4, 3), (5, 2), (6, 1)]

然后遍历元组并比较每一对:

first = (1,2,3,4,5,6)
last = (6,5,4,3,2,1)

for l1,l2 in zip(first,last):
    if l1 < l2:
        print("l1 < l2")
    elif l1 > l2:
        print("l2 > l1")
    elif l1 == l2:
        print("l1 == l2")

输出:

l1 < l2
l1 < l2
l1 < l2
l2 > l1
l2 > l1
l2 > l1

另一种方法是迭代索引,但是这种方法不那么 Pythonic:

for i in range(len(first)):
    l1 = first[i]
    l2 = last[i]
    if l1 < l2:
        print("l1 < l2")
    elif l1 > l2:
        print("l2 > l1")
    elif l1 == l2:
        print("l1 == l2")

【讨论】:

  • 如果你想知道它们是否都相等 all( [l[0] == l[1] for l in list(zip(a,b))] ) == True。解释:由内而外。 zip 在一起,然后将 zip 转换为元组列表。使用列表推导比较它们。最后 all 检查它们是否都相等
  • 如果我遇到列表长度不同的情况,我如何通过返回短列表的第一个元素以匹配长列表的下一个元素来循环迭代?
【解决方案2】:

你应该用zip将这两个元组组合成一个两元素成对元组的列表:

for x, y in zip(first, last):
    if x < y: ... # Your code

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-01-07
    • 1970-01-01
    • 1970-01-01
    • 2019-12-07
    • 1970-01-01
    • 2020-07-04
    相关资源
    最近更新 更多