数组中相似项的序列

Sequence of similar items in an array

我是第一次在 Python 工作,我需要找到一种有效的方法来搜索由三个、四个或五个元素组成的连续序列在更大的数组中是否相同。

例如:

array = [1, 0, 0, 0, 1]

输出:

number_same = 3
element = 0
positions = [1, 2, 3]

有什么建议或帮助吗?

谢谢!

我不太了解 Python,但我不认为有内置功能可以完成此操作。

您可以遍历列表并使用第二个数组作为计数器。

即如果位置0的数字是1,则将1添加到第二个数组中的位置1

original_array = [1, 0, 0, 0, 1]
second_array_after_populating = [3, 2, 0, 0, 0]

然后您只需扫描列表一次即可找到最常见的号码,以及该号码的数量。知道数字后,您可以回头浏览原始列表以找到它出现的位置。

我认为 Counter class 对你有用。

from collections import Counter
array = [1, 0, 0, 0, 1]
counter = Counter(array)
mc = counter.most_common(20)
print(mc)

# [(0, 3), (1, 2)]
most_common = mc[0][0] #  = 0
number_same = mc[0][1] #  = 3
positions = [i for i, x in enumerate(array) if x == most_common]

最后一行来自SO post

这不是一个完整的答案,但它是一个开始。

这使用与 itertools 库关联的 groupby() 方法。 groupby() 方法查找连续的值组(与真正的值组相对),因此它非常适合查找序列。

array = [1, 0, 0, 0, 1]

from itertools import groupby

g = groupby(array)
for value, grp in g:

grp 是一个迭代器...我们可以通过使用 list() 函数将其转换为将值提取到列表中来公开内容。

    grp = list(grp)
    length = len(grp)

使用 inif 语句是检查各种值的便捷方法。

    if length in [3, 4, 5]:
        print('number_same =', length)
        print('element =', value)
        print('positions =', 'still working on this')

==== OUTPUT ====
number_same = 3
element = 0
positions = still working on this

下一行将为您提供一个值的元组列表及其在数组中的位置(按重复分组):

from itertools import groupby
[(k, [x[0] for x in g]) for k, g in groupby(enumerate(array), lambda x: x[1])]
>>> [(1, [0]), (0, [1, 2, 3]), (1, [4])]

您稍后可以过滤它以仅获得 3 次及以上的重复:

filter(lambda x: len(x[1])>2, grouped_array)

参考了以下答案: What's the most Pythonic way to identify consecutive duplicates in a list?