简体   繁体   中英

Compare corresponding elements of a list

I am trying to perform a simple comparison between 2 lists. How do I compare one elements from list A to the corresponding element of list B? Lets say I have 2 lists.

A = [100,100,100]

B = [100,120,95]

I want to compare lists A and B (A[1] with B[1], A[2] with B[2] and so on).

A = [100,100,100]
B = [100,120,95]

if A <= B:
    print("A is less than or equal to B")
else:
    print("A is not less than B")

I expect "A is not less than B" to be the output but it prints "A is less than or equal to B" which is not correct. Please help!

Function zip will generate for you pairs of elements:

>>> print(list(zip(A, B)))
[(100, 100), (100, 120), (100, 95)]

Now you can run an easy pairwise comparison using a list comprehension :

>>> [a > b for (a, b) in zip(A, B)]
[False, False, True]

Now you easily can check whether the comparison holds for every element:

>>> all(a > b for (a, b) in zip(A, B))
False

I hope this helps.

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