How to compare two adjacent items in the same list - Python

前端 未结 4 1001
鱼传尺愫
鱼传尺愫 2021-01-03 00:34

I am searching for a way to compare two adjacent items in a list, eg. comparing which has a higher value, and then I will sort them accordingly. It is a list the user will b

4条回答
  •  清酒与你
    2021-01-03 01:30

    there is built in function cmp, which you can use for the comparison

    I needed to check if all items in list are identical, so I did this:

    def compare(x, y):
        if x == y:
            return x
        return False
    
    reduce(compare, my_list)
    

    When you run this with say [1,1,1,1,1,1], it prints 1, when one of numbers doesn't match, it returns False .. simple

提交回复
热议问题