Compare corresponding elements of a list

前端 未结 1 705
离开以前
离开以前 2021-01-29 12:50

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

1条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-01-29 13:43

    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.

    0 讨论(0)
提交回复
热议问题