<分区>
我想对这个数字列表进行切片:
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]
谁能帮我解决这个问题?非常感谢
标签 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/