[英]How to fix this failing recursion? (Python, recursion, nested lists)
澄清:根据提出的问题添加一些澄清:更大的过程 - 我的用户观看视频,并在视频播放时按下键盘键。 每次他们敲击键盘时,视频的时间戳(以毫秒为单位)都会记录在一个列表中。 该视频由许多连接在一起的小视频组成(每个视频大约是 20-60 秒的试用版)。 计算机不知道试验是什么(对于计算机来说,这只是一个长视频),但用户确实知道试验。 我需要根据试验的时间范围划分这个列表,但这里没有规则 - 值的总和不应该是任何东西,一个试验可以有 6 个时间戳,另一个可以有 38 个。我只需要划分这么大值列表,基于它们所代表的时间范围(= 它们参与的试验)
trial_num 只是为了知道我有多少可能的范围 - 而不是运行无限次,而是根据我拥有的试验量(时间范围)运行它。 它最终应该转化为我最终拥有的子列表的数量(因为每个试验中的时间应该写入一个单独的子列表)
trial_length 是给我需要划分的每个时间范围的长度 - 在我这里的例子中,如果我的试验长度是 5 秒,即 5000 毫秒,我的范围将是 0-5000、5001- 10000, 10001-15000 等等...所以,试验长度是每个范围的大小,而试验数是我拥有的范围数(可以看作是 n,然后 n*trial_length 给出了我所在的范围)
*原始问题:我正在尝试执行以下操作:我有一个值列表(如果重要,浮动,代表视频中的毫秒)。 我需要根据列表中的值进行划分,但是我有很多范围,每个范围应该是最终列表中的不同子列表。
我的代码如下:
def break_lists(orig_list, trial_length, trials_num, final_list):
# This section builds a list of the number of sublists I should have, the number of ranges I will work with.
t = []
for num in range(1, trials_num + 1):
t.append(num)
# take the given range and multiply by 1000 (user will give in seconds and my list is in ms)
ms_length = trial_length * 1000
# loop through the number of trials that I have (sublists)
for num in t:
# create a new sublist each time
sublist = []
# loop through values 0-40 in my list (max values per sublist will be 40, but could be less!)
for i in range(0, 40):
# check if value in original list is smaller than the highest border of the range
if orig_list[i] <= ms_length * num:
# if it is, add it to the sublist
sublist.append(orig_list[i])
else:
# if it's not, call the function again starting from the last value you got to on the original list
break_lists(orig_list[i:], trial_length, trials_num, final_list)
final_list.append(sublist)
print(final_list)
return(final_list)
当我使用这个列表时: list = [2000, 3000, 4000, 5000, 6000, 7000, 9000, 12000, 15000, 17000, 19000, 80000]
并调用函数: break_lists(list, 5, 20, [])
我的目标是让它成为这个final_list = [[2000, 3000, 4000, 5000], [6000, 7000, 9000], [12000, 15000], [17000, 19000], [80000]]
此刻(以及沿途的许多其他时刻)我收到消息说“比较超出了最大递归深度”。 我一直在玩并更改它以试图找出问题,所以有时我确实会得到一个包含我的值的列表,但是列表中的值之间有许多空列表(超过试验次数),我不知道为什么
我确信有数万亿种方法可以做到这一点,可能比我在这里得到的更有效,但我的大脑对此有点厌倦并坚持那个递归的想法。 我也是新来的,不知道可能对我的问题有简单解决方案的包或模块。 任何想法将不胜感激! (我也想过在从用户那里获取值时将它们分开,但我相信它基本上是相同的,并且在单独的函数中而不是在另一个函数中进行分离可能会更好)
感谢您阅读到这里并为您提供帮助!!!
国际大学联盟:
代码
def break_lists(orig_list, trial_length, trials_num):
result = [[] for _ in range(trials_num)] # Create ranges
for v in orig_list:
bin_ = int(v/(trial_length*1000)) # find bin
if bin_*trial_length*1000 == v:
bin_ -= 1 # bin should include right edge
result[bin_].append(v) # Add data to bin
return result
测试
print(break_lists(orig_list, 5, 20))
# Output:
[[2000, 3000, 4000, 5000],
[6000, 7000, 9000],
[12000, 15000],
[17000, 19000],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[80000],
[],
[],
[],
[]]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.