Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/317.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 基于条件创建列表列表_Python_List_Conditional Statements - Fatal编程技术网

Python 基于条件创建列表列表

Python 基于条件创建列表列表,python,list,conditional-statements,Python,List,Conditional Statements,我有一个列表,其中包含一些递增到某个值的数字,然后以某种方式重复相同的行为,但没有周期性。我需要根据输入创建一个代表这些组的列表列表 输入: 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] 期望输出 [[2, 5, 6, 9, 10, 11, 13, 18, 19, 21], [3, 5, 8, 9, 12, 17, 119],

我有一个列表,其中包含一些递增到某个值的数字,然后以某种方式重复相同的行为,但没有周期性。我需要根据输入创建一个代表这些组的列表列表

输入:

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] 
期望输出

[[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]]
我提出了这段代码,但起初我无法在没有明确干预的情况下将最后一次迭代转储到列表中。你能想出更好的办法吗

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])

如果输出为空或当前项少于最后一个子列表中的最后一项,则可以追加新的子列表:

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=[]
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\u of_lists=[[index[0]]]
并迭代其余的值来消除
not list\u of_lists
部分,这将使代码不那么通用,因为它要求
index
不为空。此外,“迭代其余的值”意味着必须切片,这也是一种开销。检查
索引的空性可以在开始时完成,开销可以通过迭代列表索引或使用iteratorTrue解决,虽然这听起来像是一个微优化,使得代码不必要地缺乏可读性,而没有有意义的增益。事实证明临时lst是不必要的,诀窍是将结果附加为一个带有append([])的列表。我们可以通过初始化
list\u of\u list=[[index[0]]]
并迭代其余的值来消除
not list\u of\u list
部分,这将使代码不那么通用,因为它要求
index
不为空。此外,“迭代其余的值”意味着必须切片,这也是一种开销。检查
索引的空性可以在开始时完成,开销可以通过迭代列表索引或使用iteratorTrue解决,虽然这听起来像是一个微优化,使得代码不必要地缺乏可读性,而没有有意义的增益。事实证明临时lst是不必要的,诀窍是将结果附加为一个带有append([])的列表。感谢@blhsing。