📜  Python – 在下一个较大的值上拆分列表

📅  最后修改于: 2022-05-13 01:55:06.992000             🧑  作者: Mango

Python – 在下一个较大的值上拆分列表

给定一个列表,对下一个较大的值执行拆分。

方法:使用循环

在此,我们迭代列表并跟踪拆分值,如果找到高于记录值的值,则从中创建新列表,拆分值是当前值。

Python3
# Python3 code to demonstrate working of 
# Split List on next larger value
# Using loop
  
# initializing list
test_list = [4, 2, 3, 7, 5, 9, 3, 4, 11, 2]
  
# printing original list
print("The original list is : " + str(test_list))
  
# starting value as ref.
curr = test_list[0]
temp = []
res = []
for ele in test_list:
      
    # if curr value greater than split
    if ele > curr:
        res.append(temp)
        curr = ele
        temp = []
    temp.append(ele)
res.append(temp)
  
# printing results
print("Split List : " + str(res))


输出
The original list is : [4, 2, 3, 7, 5, 9, 3, 4, 11, 2]
Split List : [[4, 2, 3], [7, 5], [9, 3, 4], [11, 2]]