将整数列表分解为递增序列列表

2024-02-26 12:03:53 发布

您现在位置:Python中文网/ 问答频道 /正文

假设列表中没有连续整数

我已经尝试使用NumPy(np.diff)来表示每个元素之间的差异,但是没有能够使用它来获得答案。下面是输入(第一行)和预期输出(第二行)的两个示例

[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]]

Tags: 答案numpy元素示例列表npdiff整数
3条回答

您可以使用^{}在列表中的顺序元素对上启用迭代,同时使用enumerate跟踪序列没有增加的索引值,以便将相应的片段附加到输出列表中

from itertools import zip_longest

nums = [1, 4, 1, 2, 4, 3, 5, 4, 0]

results = []
start = 0
for i, (a, b) in enumerate(zip_longest(nums, nums[1:])):
    if b is None or b <= a:
        results.append(nums[start:i+1])
        start = i + 1

print(results)
# [[1, 4], [1, 2, 4], [3, 5], [4], [0]]

以下是一种简单的方法,可以在不使用任何额外库的情况下完成您的要求:

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)

只是因为我感觉亲切,这也适用于负数

seq = [6, 0, 4, 8, 7, 6]
seq_by_incr_groups = []  # Will hold the result
incr_seq = []  # Needed to create groups of increasing values.
previous_value = 0  # Needed to assert whether or not it's an increasing value. 
for curr_value in seq: # Iterate over the list
    if curr_value > previous_value: # It's an increasing value and belongs to the group of increasing values.
        incr_seq.append(curr_value)
    else:  # It was lower, lets append the previous group of increasing values to the result and reset the group so that we can create a new one.
        if incr_seq:  # It could be that it's empty, in the case that the first number in the input list is a negative.
            seq_by_incr_groups.append(incr_seq)
        incr_seq = []
        incr_seq.append(curr_value)
    previous_value = curr_value # Needed so that we in the next iteration can assert that the value is increasing compared to the prior one.

if incr_seq:  # Check if we have to add any more increasing number groups.
    seq_by_incr_groups.append(incr_seq)  # Add them.

print(seq_by_incr_groups)

相关问题 更多 >