检查列表中的任何相邻整数是否相等

编程入门 行业动态 更新时间:2024-10-14 00:25:59
本文介绍了检查列表中的任何相邻整数是否相等的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

如果我有列表

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.

更多推荐

检查列表中的任何相邻整数是否相等

本文发布于:2023-11-29 22:20:38,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1647799.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:整数   列表中

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!