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

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

    You can use zip():

    In [23]: lis = [1,7,8,4,5,3]
    
    In [24]: for x, y in zip(lis, lis[1:]):
       ....:     print x, y           # prints the adjacent elements
                 # do something here
       ....:     
    1 7
    7 8
    8 4
    4 5
    5 3
    
    0 讨论(0)
  • 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. :)

    0 讨论(0)
  • 2021-01-03 01:29

    The quick-and-ugly solution would be this (don't use it!):

    for i, item in enumerate(lst):
        # here you can use lst[i + 1] as long as i + 1 < len(lst)
    

    However, do not implement list sorting by yourself! Use .sort() to sort in-place or sorted() if you want to create a new list instead. There is a really good guide on how to sort things on the python website.

    If that's not your intention.. instead of the loop I posted above there's also a much nicer way to iterate over chunks from a list in another SO question:

    import itertools
    def grouper(n, iterable, fillvalue=None):
        "grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx"
        args = [iter(iterable)] * n
        return itertools.izip_longest(fillvalue=fillvalue, *args)
    

    You use to like this:

    for x, y in grouper(2, lst):
        # do whatever. in case of an odd element count y is None in the last iteration
    
    0 讨论(0)
  • 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

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