在数字列表中找到相同数字的重复模式

find repeating patterns of same number in a list of numbers

我正在尝试在列表编号中查找相同编号的重复模式。 例如

flag_list = [6, 4, 4, 20, 4, 4, 4, 4, 22, 0, 0, 0, 0, 0, 0, 16, 0, 0, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 16]

期望的输出:它将是所有重复数字列表的列表。 例如

repeating_list = [[4, 4],
                  [4, 4, 4, 4],
                  [0, 0, 0, 0, 0, 0],
                  [0, 0],
                  [16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16],
                  [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
                  ]

我试过这些行:

main_list = []
temp = []
for i in range(0,len(flag_list)):
   
    if flag_list[i-1]==flag_list[i]:
        if flag_list[i-1] not in temp:
            temp.append(flag_list[i-1])
        temp.append(flag_list[i])
 
    main_list.append(temp)
    temp.clear()

请分享与此相关的任何资源,这将有很大帮助。谢谢

理想情况下,使用 itertools.groupby:

flag_list = [6, 4, 4, 20, 4, 4, 4, 4, 22, 0, 0, 0, 0, 0, 0, 16, 0, 0,
             16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16,
             16, 16, 16, 16, 16, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
             0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
             0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 16]

from itertools import groupby

[G for _,g in groupby(flag_list) if len(G:=list(g))>1]

注意。此代码使用 assignment expression 并要求 python ≥ 3.8

或按照@wjandrea 的建议使用 extended iterable unpacking,与 python ≥ 3.0:

兼容
[g for _k, (*g,) in groupby(flag_list) if len(g) > 1]

输出:

[[4, 4],
 [4, 4, 4, 4],
 [0, 0, 0, 0, 0, 0],
 [0, 0],
 [16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16],
 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
]
变体格式

如果格式 (value, number_repeats),您可以轻松地“压缩”输出:

[(n, len(G)) for n,g in groupby(flag_list) if len(G:=list(g))>1]

输出:

[(4, 2), (4, 4), (0, 6), (0, 2), (16, 19), (0, 46)]