如何在python列表中找到最长的一致增量? [英] How to find longest consistent increment in a python list?

查看:51
本文介绍了如何在python列表中找到最长的一致增量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

possible_list = []更大的列表 = []new_list= [0, 25, 2, 1, 14, 1, 14, 1, 4, 6, 6, 7, 0, 10, 11]对于范围内的 i(0,len(new_list)):# 如果下一个索引不大于列表的长度如果 (i + 1) <(len(new_list)):#如果当前值小于下一个值如果 new_list[i] <= new_list[i+1]:# 将当前值添加到这个子列表possible_list.append(new_list[i])# 如果当前值大于下一个值,则关闭列表并将其附加到更大的列表中更大的列表.追加(可能的列表)打印更大的列表

如何在名为 new_list 的列表中找到最长的一致增量?我希望结果是

[[0,2], [2], [1,14], [1,14], [1,4,6,6,7], [0,10,11]]

我可以自己从那里找到剩余的解决方案.

解决方案

您的代码的一个问题(但不是唯一的)是您总是将元素添加到相同 可能的列表,因此bigger_list中的列表实际上都是同一个列表!

相反,我建议使用 [-1] 访问子序列列表的最后一个元素(即要附加到的元素)和 [-1][-1] 访问该子序列的最后一个元素(用于与当前元素进行比较).

new_list= [0, 25, 2, 1, 14, 1, 14, 1, 4, 6, 6, 7, 0, 10, 11]子序列 = [[]]对于 new_list 中的 e:如果不是 subseq[-1] 或 subseq[-1][-1] <= e:subseq[-1].append(e)别的:subseq.append([e])

这样,subseq 会按照你想要的方式结束,你可以使用 max 来得到最长的.

<预><代码>>>>子序列[[0, 25], [2], [1, 14], [1, 14], [1, 4, 6, 6, 7], [0, 10, 11]]>>>最大(子序列,键= len)[1, 4, 6, 6, 7]

possible_list = []
bigger_list = []

new_list= [0, 25, 2, 1, 14, 1, 14, 1, 4, 6, 6, 7, 0, 10, 11]
for i in range(0,len(new_list)):
   # if the next index is not greater than the length of the list
    if (i + 1) < (len(new_list)):
         #if the current value is less than the next value
         if new_list[i] <= new_list[i+1]:
             # add the current value to this sublist
             possible_list.append(new_list[i])
             # if the current value is greater than the next, close the list and append it to the lager list
         bigger_list.append(possible_list)
print bigger_list

How do I find the longest consistent increment in the list called new_list? I expect the result to be

[[0,2], [2], [1,14], [1,14], [1,4,6,6,7], [0,10,11]]

I can find the remaining solution from there myself.

解决方案

One problem (but not the only one) with your code is that you are always adding the elements to the same possible_list, thus the lists in bigger_list are in fact all the same list!

Instead, I suggest using [-1] to access the last element of the list of subsequences (i.e. the one to append to) and [-1][-1] to access the last element of that subsequence (for comparing the current element to).

new_list= [0, 25, 2, 1, 14, 1, 14, 1, 4, 6, 6, 7, 0, 10, 11]    
subseq = [[]]
for e in new_list:
    if not subseq[-1] or subseq[-1][-1] <= e:
        subseq[-1].append(e)
    else:
        subseq.append([e])

This way, subseq ends up the way you want it, and you can use max to get the longest one.

>>> subseq
[[0, 25], [2], [1, 14], [1, 14], [1, 4, 6, 6, 7], [0, 10, 11]]
>>> max(subseq, key=len)
[1, 4, 6, 6, 7]

这篇关于如何在python列表中找到最长的一致增量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆