python - 根据条件将列表分成子列表

标签 python python-3.x list

<分区>

我想对这个数字列表进行切片:

num_list = [97, 122, 99, 98, 111, 112, 113, 100, 102] 

分成多个子列表。切片的条件是每个子列表中的数字应该是递增的。

所以最终的结果是这样的:

 list_1 = [97, 122]
 list_2 = [99]
 list_3 = [98, 111, 112, 113]
 list_4 = [100, 102]

谁能帮我解决这个问题?非常感谢

最佳答案

我已经快速编写了一种方法来执行此操作,我相信还有更有效的方法,但这至少有效:

num_list =[97, 122, 99, 98, 111, 112, 113, 100, 102]

arrays = [[num_list[0]]] # array of sub-arrays (starts with first value)
for i in range(1, len(num_list)): # go through each element after the first
    if num_list[i - 1] < num_list[i]: # If it's larger than the previous
        arrays[len(arrays) - 1].append(num_list[i]) # Add it to the last sub-array
    else: # otherwise
        arrays.append([num_list[i]]) # Make a new sub-array 
print(arrays)

希望这对您有所帮助:)

关于python - 根据条件将列表分成子列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52551398/

相关文章:

Python:使用模块 laspy 的列表理解问题

java - 列表输出不正确

python - 为什么它在我的 Tkinter 程序中显示空白而不是图片?

python - 如何过滤字符串?

python - python 中的多终端处理

python - 如何在python中检查目录是否有音乐文件?

python - ImportError : Model A references Model B, 模型 B 引用模型 A

python tkinter 从命令中使用的函数返回值

python - 'number % 2:' 和 'number % 2 == 0' 之间的区别?

c - C 中 ADT 列表迭代器的问题