比较Python中的两个列表元素



我有两个列表

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

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

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

另一种方法是在索引上迭代,但是这种方法较少:

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")

您应该将两个元组结合到具有zip的两元素,成对元组的列表中:

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

最新更新