[英]creating a list of lists based on a condition
I have a list containing some numbers increasing until a certain value, and then somehow repeating the same behavior but nothing periodic.我有一个列表,其中包含一些数字,直到某个值,然后以某种方式重复相同的行为,但没有周期性。 I need to create a list of lists representing these groups from the input.我需要从输入中创建代表这些组的列表列表。
input:输入:
index=[2,5,6,9,10,11,13,18,19,21, 3,5,8,9,12,17,119, 2,4,6,8,10,12,14,16,18,200, 3,5,7,9,11,14,15,19,233]
desired_output期望输出
[[2, 5, 6, 9, 10, 11, 13, 18, 19, 21],
[3, 5, 8, 9, 12, 17, 119],
[2, 4, 6, 8, 10, 12, 14, 16, 18, 200],
[3, 5, 7, 9, 11, 14, 15, 19, 233]]
I came up with this code but at first I couldn't manage to dump the last iteration to the list_of_lists without explicit intervention.我想出了这段代码,但起初我无法在没有明确干预的情况下将最后一次迭代转储到 list_of_lists 中。 Can you think a better way to do it?你能想出更好的方法吗?
temp_lst=[]
list_of_lists=[]
for i in range(len(index)-1):
if index[i+1]>index[i]:
temp_lst.append(index[i])
else:
temp_lst.append(index[i])
list_of_lists.append(temp_lst)
temp_lst=[]
list_of_lists.append(temp_lst)
list_of_lists[-1].append(index[-1])
You can append a new sub-list if the output is empty or if the current item is less than the last item in the last sub-list:如果 output 为空或当前项小于最后一个子列表中的最后一项,您可以 append 一个新的子列表:
list_of_lists=[]
for i in index:
if not list_of_lists or i < list_of_lists[-1][-1]:
list_of_lists.append([])
list_of_lists[-1].append(i)
list_of_lists
becomes: list_of_lists
变为:
[[2, 5, 6, 9, 10, 11, 13, 18, 19, 21],
[3, 5, 8, 9, 12, 17, 119],
[2, 4, 6, 8, 10, 12, 14, 16, 18, 200],
[3, 5, 7, 9, 11, 14, 15, 19, 233]]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.