识别列表是否具有相等的连续元素 [英] Identify if list has consecutive elements that are equal

查看:32
本文介绍了识别列表是否具有相等的连续元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试确定一个大型列表是否具有相同的连续元素.

所以我们说:

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

在这种情况下,我将返回true,因为有两个连续的元素 lst [4] lst [5] 具有相同的值.

我知道这可以通过某种形式的循环组合来完成,但是我想知道是否有更有效的方法来做到这一点?

解决方案

您可以使用itertools.groupby()any() 中的生成器表达式 * :

 >>>从itertools导入groupby>>>任何(sum(1(对于g中的_,1))> 1对于_,g在groupby(lst)中)真的 

或者以一种更Python化的方式,可以使用 zip()来检查列表中是否至少有两个相等的连续项:

 >>>any(i = i表示zip(lst,lst [1:]))中的i,j#在python-2.x中,为了避免创建所有对的列表"而不是迭代器,请使用itertools.izip()真的 

注意:当您要检查是否有两个以上的连续相等项目时,第一种方法是好的,否则,在这种情况下,第二种方法就很容易做到!


*使用 sum(1表示g中的_)代替 len(list(g))在内存使用方面非常优化(不读取整个列表一次存储在内存中),但后者要快一些.

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

So let's say:

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

And in this case, I would return true, since there are two consecutive elements lst[4] and lst[5], are the same value.

I know this could probably be done with some sort of combination of loops, but I was wondering if there were a more efficient way to do this?

解决方案

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.

这篇关于识别列表是否具有相等的连续元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆