问题描述
我有一个数字列表,例如:
I have a list of numbers, for example:
list= [1, 2, 4, 1, 2, 4, 1, 2, 4]
您可以看到1,2,4的明显重复模式
You can see the obvious repeating pattern of 1,2,4
我正在尝试找到一种方法来遍历该列表,以确定周期及其长度.数字在我的程序中每次都不同.例如,我给出的列表希望它输出3,即模式的长度.
I'm trying to find a way to go through that list to determine the cycle and it's length. The numbers vary every time in my program. So for example, the list that I give, I want it to output 3, which is the length of the pattern.
我尝试将项目进行比较,但最终无法找到一种有效的方法,而不必每次都退出列表索引,因为我只是在寻找序列中重复的数字.这样做的问题是,模式可能类似于2 2 1,在这种情况下,我实际上将输出2作为模式长度,而实际上是3.
I tried comparing the items together, but ultimately couldn't figure out a way to do it efficiently without going out of the list index every time, because I was just looking for when a number repeated in the sequence. The problem with that was that the pattern could be something like 2 2 1, in which case i would have outputted 2 as the pattern length, when it was actually 3.
很抱歉,由于缺少信息,我不知道该怎么做,所以没有太多示例代码可供显示.
Sorry for the lack of information, I'm lost as to how to do this so I don't have much sample code to show.
推荐答案
您可以使用生成器函数将您的列表分成多个块.
You can use a generator function to split your list into chunks.
>>> def gen(lst, pat):
... size = len(pat)
... size_l = len(lst)
... for i in range(0, size_l, size):
... yield lst[i:i+size]
...
>>> lst = [1, 2, 4, 1, 2, 4, 1, 2, 4]
>>> pat = [1, 2, 4]
>>> len(list(gen(lst, pat)))
3
也不要使用列表"作为变量的名称,它会隐藏内置的list
class
Also don't use "list" as variable's name it will shadow the built-in list
class
这篇关于从列表中查找整数模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!