gpt4 book ai didi

python - 查找列表中重复序列索引的有效方法?

转载 作者:行者123 更新时间:2023-12-02 04:04:49 28 4
gpt4 key购买 nike

我在 python 中有一个很大的数字列表,我想编写一个函数来查找列表中相同数字重复超过 n 次的部分。例如,如果 n 为 3,则我的函数应为以下示例返回以下结果:

When applied to example = [1,2,1,1,1,1,2,3] the function should return [(2,6)], because example[2:6] is a sequence containing all the same value.

When applied to example = [0,0,0,7,3,2,2,2,2,1] the function should return [(0,3), (5,9)] because both example[0:3] and example[5:9] contain repeated sequences of the same value.

When applied to example = [1,2,1,2,1,2,1,2,1,2] the function should return [] because there is no sequence of three or more elements that are all the same number.

我知道我可以编写一堆循环来获得我想要的东西,但这似乎效率很低,我想知道是否有更简单的选择来获得我想要的东西。

最佳答案

使用itertools.groupby枚举:

>>> from itertools import groupby
>>> n = 3
>>> x = [1,2,1,1,1,1,2,3]
>>> grouped = (list(g) for _,g in groupby(enumerate(x), lambda t:t[1]))
>>> [(g[0][0], g[-1][0] + 1) for g in grouped if len(g) >= n]
[(2, 6)]
>>> x = [0,0,0,7,3,2,2,2,2,1]
>>> grouped = (list(g) for _,g in groupby(enumerate(x), lambda t:t[1]))
>>> [(g[0][0], g[-1][0] + 1) for g in grouped if len(g) >= n]
[(0, 3), (5, 9)]

要理解groupby:只需意识到每次迭代都会返回键的值,该值用于对可迭代的元素进行分组,以及一个将迭代该组的新的惰性迭代。

>>> list(groupby(enumerate(x), lambda t:t[1]))
[(0, <itertools._grouper object at 0x7fc90a707bd0>), (7, <itertools._grouper object at 0x7fc90a707ad0>), (3, <itertools._grouper object at 0x7fc90a707950>), (2, <itertools._grouper object at 0x7fc90a707c10>), (1, <itertools._grouper object at 0x7fc90a707c50>)]

关于python - 查找列表中重复序列索引的有效方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40006438/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com