Python:将整数列表分解为递增序列的列表

时间:2019-04-30 15:19:46

标签: 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]]

6 个答案:

答案 0 :(得分:3)

这是一种简单的方法,无需任何额外的库即可完成您要问的事情:

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)

答案 1 :(得分:3)

您可以使用itertools.zip_longest启用列表中顺序元素对的迭代,并使用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]]

答案 2 :(得分:2)

只是因为我感到友善,这也适用于负数。

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)

答案 3 :(得分:0)

据我所知,您可以编写一个简单的script,而您不需要numpy。请尝试下面的script。我已经在我的Ubuntu计算机上使用Python 3.6.7Python 2.7.15+对其进行了测试。

def breakIntoList(inp):
    if not inp:
        return []

    sublist = [inp[0]]
    output = []
    for a in inp[1:]:
        if a > sublist[-1]:
            sublist.append(a)
        else:
            output.append(sublist);
            sublist = [a]


    output.append(sublist)
    return output



list = [1, 4, 1, 2, 4, 3, 5, 4, 0]
print(list)
print(breakIntoList(list))

说明:

  1. 脚本首先检查传递给它的输入List是否具有一个或多个元素。
  2. 然后初始化一个子列表(variable name)以按递增顺序保存元素。之后,我们将输入列表的第一个元素添加到子列表中。
  3. 我们从输入List的第二个元素(Index: 1)开始迭代。我们继续检查输入列表中的当前元素是否大于子列表的最后一个元素(按sublist[-1])。如果是,则将当前元素附加到我们的子列表中(最后)。如果不是,则意味着我们不能将当前元素保存在子列表中。我们将子列表追加到输出列表中,并清除子列表(用于保存其他递增顺序的子列表),然后将当前元素添加到我们的子列表中。
  4. 最后,我们将剩余的子列表追加到输出列表中。

答案 4 :(得分:0)

下面的代码应该可以为您提供帮助。但是,我建议您使用适当的术语,并考虑处理极端情况。

li1 = [6, 0, 4, 8, 7, 6]
li2 = [1, 4, 1, 2, 4, 3, 5, 4, 0]

def inc_seq(li1):
  lix = []
  li_t = [] 
  for i in range(len(li1)):
    #print (i)
    if i < (len(li1) - 1) and li1[i] >= li1[i + 1]:
      li_t.append(li1[i])
      lix.append(li_t)
      li_t = []
    else:
      li_t.append(li1[i])


  print (lix)
inc_seq(li1)
inc_seq(li2)

答案 5 :(得分:0)

以下是使用dict,列表推导和zip的替代方法:

seq = [1, 4, 1, 2, 4, 3, 5, 4, 0]
dict_seq = {i:j for i,j in enumerate(seq)}

# Get the index where numbers start to decrease
idx = [0] # Adding a zero seems counter-intuitive now; we'll see the benefit later.
for k, v in dict_seq.items():
    if k>0:
        if dict_seq[k]<dict_seq[k-1]:
            idx.append(k)

# Using zip, slice and handling the last entry
inc_seq = [seq[i:j] for i, j in zip(idx, idx[1:])] + [seq[idx[-1:]]]

输出

print(inc_seq)
>>> [[1, 4], [1, 2, 4], [3, 5], [4], [0]]

通过启动idx = [0]并创建2个子列表idxidx[1:],我们可以zip这些子列表以列表理解的方式形成[0:2], [2:5], [5:7] and [7:8]

>>> print(idx)
>>> [0, 2, 5, 7, 8]

>>> for i, j in zip(idx, idx[1:]):
       print('[{}:{}]'.format(i,j))

[0:2]
[2:5]
[5:7]
[7:8]   # <-- need to add the last slide [8:]