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

时间:2019-05-04 19:26:49

标签: python python-3.x

我有两个清单

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

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

2 个答案:

答案 0 :(得分:0)

您应该将两个元组合并为一个两元素的成对元组,列表中的zip

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

答案 1 :(得分:0)

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

另一种方法是遍历索引,但是这种方法不太像Python:

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