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

前端 未结 4 1020
鱼传尺愫
鱼传尺愫 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:27

    you can also use inbuilt reduce function

    e.g. :

    l = [1,2,3,4,5,6,7]
    
    def my_function(a,b):
        # your comparison between a and b
        # return or print values or what ever you want to do based on the comparison
    
    
    reduce(my_function, l)
    

    reduce will automatically take care of i and i + 1.

    Hope it helps. :)

提交回复
热议问题