Identify if list has consecutive elements that are equal in python

前端 未结 6 1577
情深已故
情深已故 2020-11-28 15:01

I\'m trying to identify if a large given list has consecutive elements that are the same.

So let\'s say

lst = [1, 2, 3, 4, 5, 5, 6]

6条回答
  •  一向
    一向 (楼主)
    2020-11-28 15:06

    You can use itertools.groupby() and a generator expression within any() *:

    >>> from itertools import groupby
    >>> any(sum(1 for _ in g) > 1 for _, g in groupby(lst))
    True
    

    Or as a more Pythonic way you can use zip(), in order to check if at least there are two equal consecutive items in your list:

    >>> any(i==j for i,j in zip(lst, lst[1:])) # In python-2.x,in order to avoid creating a 'list' of all pairs instead of an iterator use itertools.izip()
    True
    

    Note: The first approach is good when you want to check if there are more than 2 consecutive equal items, otherwise, in this case the second one takes the cake!


    * Using sum(1 for _ in g) instead of len(list(g)) is very optimized in terms of memory use (not reading the whole list in memory at once) but the latter is slightly faster.

提交回复
热议问题