简体   繁体   中英

Comparing each item in list to Other item in other list Python

illustration of comparison

i got stuck on this code, can you help me?

a = [1, 2, 3]
b = [4, 5, 6]

item = []
item.append(a)
item.append(b)

for i in range(len(item)):
    for j in range(len(item[i])):
        print('{} <= {}'.format(item[i][j], item[i+1][j]))

You can use zip to iterate over lists in parallel:

for x, y in zip(a, b):
    print(f'{x} <= {y}')

# 1 <= 4
# 2 <= 5
# 3 <= 6

If you do it for three lists, It would look like this:

for x,y,z in zip(a,b,c):
    print(f"{x} <= {y} <= {z}")

Output:

1 <= 4 <= 7
2 <= 5 <= 8
3 <= 6 <= 9

According to your illustration and assuming that the number of elements is equal on a and b , I believe the approach you are looking for is:

a = [1, 2, 3]
b = [4, 5, 6]

for i in range(len(a)):
    print(f"{a[i]} <= {b[i]}")

But if you want to obtain the result of the comparisson, you can do:

a = [1, 2, 3]
b = [4, 5, 6]

for i in range(len(a)):
    print(f"{a[i]} <= {b[i]} : {a[i] <=b [i]}")

Hopefully this will help you! :D

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM