Python – 在下一个较大的值上拆分列表
给定一个列表,对下一个较大的值执行拆分。
Input : test_list = [4, 2, 3, 7, 5, 1, 3, 4, 11, 2]
Output : [[4, 2, 3], [7, 5, 1, 3, 4], [11, 2]]
Explanation : After 4, 7 is greater, split happens at that element, and so on.
Input : test_list = [4, 2, 3, 7, 5, 1, 3, 4, 1, 2]
Output : [[4, 2, 3], [7, 5, 1, 3, 4, 1, 2]]
Explanation : After 4, 7 is greater, split happens at that element.
方法:使用循环
在此,我们迭代列表并跟踪拆分值,如果找到高于记录值的值,则从中创建新列表,拆分值是当前值。
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]]