简体   繁体   中英

Split list until the next largest number with repeat

Python coding

i want to split list shown below

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

if this list is given, i want to split it into

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

the algorithm is split until there is bigger number than 5 then 5,4,2,5 is in one list, next number is 7, so split the list until there is bigger then 7 which is 10. how can i do this?

arr = [5,4,2,5,7,5,4,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)

Prints: [[5, 4, 2, 5], [7, 5, 4], [10, 2]]

Here you are:

a=[5,4,2,5,7,5,4,10,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))

Output:

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

Test it here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM