python - 获取列表中相似连续元素的索引(Python3)

标签 python python-3.x list

我正在尝试创建一个函数,该函数返回列表中 3 个相似的连续元素的索引。对于列表 [1,2,3,3,3,4,5],输出应该是 myFunc([1,2,3,3,3,4,5]) ---> 2(或 [2] ).

以下代码完成这项工作:

def myFunc(a):
    lst = []
    for i in range(len(a)-2):
        if a[i]==a[i+1]==a[i+2]:
            lst.append(i)
    return lst

...但是检查一个大列表中的每个元素非常耗时。

代码:

def myFunc(a):
    return any(a[i]==a[i+1]==a[i+2] for i in range(len(a)-2))

...似乎对这个问题有用,但我不确定是否有办法从中获取相似连续元素的索引(返回 True 或 False)

我的问题: 有没有一种方法可以在不使用 for 循环检查每个元素的情况下确定列表中相似连续元素的索引?有没有更优雅的方法来解决这个问题?

最佳答案

您也可以使用 filter 在纯 Python 中完成此操作功能:

inList = [1,2,3,3,3,4,5]

def showIndices(inList):
    return list(filter(lambda i: inList[i] == inList[i+1] == inList[i+2], range(len(inList)-2)))

indices = showIndices(inList)
print(indices)

输出:

[2]

关于python - 获取列表中相似连续元素的索引(Python3),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51463228/

相关文章:

python - 如果坐标不超过阈值,则对列进行分组

python - 为什么列表求和(有时)比 itertools.chain 快?

python - 如何使用 reduce with list of lists

python - 如何在不加载模块的情况下获取模块信息?

python - 将 numpy 一维数组转换为邻接矩阵

python - 从下拉列表中的数据库 mysql 中选择条目,python Flask

Python 打印多个(相同的)值

python - y 轴上有双方 block 的一维热图

Python:通用 XPATH 上的 Selenium、NoSuchElementException

python - 在 Python 中运行广义最小二乘法