在python中按元素比较两个列表

ARI*_*M K 6 python python-3.x

我有两个清单

first= (1,2,3,4,5,6)
last=(6,5,4,3,2,1)
Run Code Online (Sandbox Code Playgroud)

我只需要比较相应的值。我使用了下面的代码并获得了 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)
Run Code Online (Sandbox Code Playgroud)

输出:

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
Run Code Online (Sandbox Code Playgroud)

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

glh*_*lhr 7

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

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

[(1, 6), (2, 5), (3, 4), (4, 3), (5, 2), (6, 1)]
Run Code Online (Sandbox Code Playgroud)

然后迭代元组并比较每一对:

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")
Run Code Online (Sandbox Code Playgroud)

输出:

l1 < l2
l1 < l2
l1 < l2
l2 > l1
l2 > l1
l2 > l1
Run Code Online (Sandbox Code Playgroud)

另一种方法是迭代索引,但是这种方法不那么 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")
Run Code Online (Sandbox Code Playgroud)