Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
471 views
in Technique[技术] by (71.8m points)

python - Decompose a list of integers into lists of increasing sequences

Assume no consecutive integers are in the list.

I've tried using NumPy (np.diff) for the difference between each element, but haven't been able to use that to achieve the answer. Two examples of the input (first line) and expected output (second line) are below.

[6, 0, 4, 8, 7, 6]
[[6], [0, 4, 8], [7], [6]]


[1, 4, 1, 2, 4, 3, 5, 4, 0]
[[1, 4], [1, 2, 4], [3, 5], [4], [0]]
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Here's a simple way to do what you're asking without any extra libraries:

result_list = []
sublist = []
previous_number = None

for current_number in inp:
    if previous_number is None or current_number > previous_number:
        # still ascending, add to the current sublist
        sublist.append(current_number)
    else:
        # no longer ascending, add the current sublist 
        result_list.append(sublist)

        # start a new sublist
        sublist = [current_number]
    previous_number = current_number
if sublist:
    # add the last sublist, if there's anything there
    result_list.append(sublist)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...