简体   繁体   English

比较列表的对应元素

[英]Compare corresponding elements of a list

I am trying to perform a simple comparison between 2 lists.我正在尝试在 2 个列表之间进行简单的比较。 How do I compare one elements from list A to the corresponding element of list B?如何将列表 A 中的一个元素与列表 B 中的相应元素进行比较? Lets say I have 2 lists.假设我有 2 个列表。

A = [100,100,100] A = [100,100,100]

B = [100,120,95] 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 和 B(A[1] 与 B[1],A[2] 与 B[2] 等等)。

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.我希望“A 不小于 B”是输出,但它打印“A 小于或等于 B”,这是不正确的。 Please help!请帮忙!

Function zip will generate for you pairs of elements:函数zip将为您生成元素对:

>>> 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.我希望这有帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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