比较列表中的相应元素 [英] Compare corresponding elements of a list
问题描述
我正在尝试对2个列表进行简单的比较.如何将列表A中的一个元素与列表B中的相应元素进行比较?可以说我有2个列表.
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]
A = [100,100,100]
B = [100,120,95]
B = [100,120,95]
我想比较列表A和B(A [1]与B [1],A [2]与B [2]等).
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")
我希望输出"A不小于B",但它会打印"A小于或等于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!
推荐答案
功能 zip
将为您生成一对元素:
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
我希望这会有所帮助.
这篇关于比较列表中的相应元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!