检查列表中的任何相邻整数是否相等 [英] Check if any adjacent integers in list are equal

查看:86
本文介绍了检查列表中的任何相邻整数是否相等的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有列表

a = [9,4,3,6,4,4,3,6,4] 

如何检查相邻的两个元素是否相同? 例如,对于索引4和5的元素(它们都具有值4)都是正确的.

解决方案

pairs = zip(a, a[1:]) # Create tuples of neighbours
equals = map(lambda (x, y): x == y, pairs) # List of booleans which tells whether tuple elements are equal or not
hasEqualNeighbours = any(equals) # Is there a True boolean in the list?

或导入eq函数并代替lambda使用,并意识到 map 可以一次遍历多个列表,因此您不需要zip:

from operator import eq
hasEqualNeigbours = any(map(eq, a, a[1:]))

如果您使用的是Python 2,也可以在from future_builtins import map上打个招呼.这使map成为了一个懒惰的迭代器,而不是构建完整的对列表,从而节省了RAM和运行时间.

If I have a list

a = [9,4,3,6,4,4,3,6,4] 

how can I check if any two neighboring elements are the same? For the example, this would be true for the elements at index 4 and 5 (which both have the value 4).

解决方案

pairs = zip(a, a[1:]) # Create tuples of neighbours
equals = map(lambda (x, y): x == y, pairs) # List of booleans which tells whether tuple elements are equal or not
hasEqualNeighbours = any(equals) # Is there a True boolean in the list?

Or import the eq function and use instead of the lambda, and realize that map can iterate over multiple lists at once so you don't need zip:

from operator import eq
hasEqualNeigbours = any(map(eq, a, a[1:]))

You can also smack on an from future_builtins import map if you are on Python 2. That makes map a lazy iterator instead of building the entire list of pairs, saving you RAM and perhaps runtime.

这篇关于检查列表中的任何相邻整数是否相等的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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