拆分列表,直到重复的下一个最大数字

问题描述

Python编码

我想拆分下面显示的列表

a=[5,4,2,5,7,10,2]

如果提供此列表,我想将其拆分为

b=[[5,5],[7,4],[10,2]]

将算法拆分为大于5的数字,然后在一个列表中有5,5, 下一个数字是7,因此请拆分列表,直到有更大的数字,然后是7,即10。 我该怎么办?

解决方法

arr = [5,4,2,5,7,10,2]

current = arr[0]
temp = []
res = []
for num in arr:
    if num > current:
        res.append(temp)
        current = num
        temp = []
    temp.append(num)
res.append(temp)
print(res)

打印: [[5,5],[7,4],[10,2]]

,

您在这里:

a=[5,2]

def split(values,threshold):
    splitted = [[]]
    for i in range(len(values)):
        if values[i] > threshold:
            threshold = values[i]
            splitted.append([])
        splitted[-1].append(values[i])
    return splitted

print(split(a,5))

输出:

[[5,2]]

测试here

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...