逆序递增数字 [英] Reversing order in incrementing digits

查看:99
本文介绍了逆序递增数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数字列表,我正在尝试以尽可能高效的方式进行以下操作.

I have a list of numbers, and I'm trying to do the following in a way as efficient as possible.

对于列表中每个连续递增的块,我必须颠倒其顺序.

For each consecutively incrementing chunk in the list I have to reverse its order.

这是我到目前为止的尝试:

This is my attempt so far:

l = []
l_ = []
i = 0
while i <= len(a)-1:
    if a[i] < a[i+1]:
        l_= l_ + [a[i]]
    else:
        l = l_ + [a[i]]
        l_ = []
    i = i + 1

我将不胜感激任何指导或其他方法.

I'd appreciate any guidance or other approaches.

因此,对于以下列表:

a = [1,5,7,3,2,5,4,45,1,5,10,12]

我想获得:

[7,5,1,3,5,2,45,4,12,10,5,1]     

推荐答案

尝试一下:

(带有@Scott Boston和@myrmica的修复程序)

(with fixes from @Scott Boston and @myrmica)

nums = [1, 3, 5, 4, 6, 8, 9, 7, 2, 4] # sample input
chunk = []    # keep track of chunks
output = []   # output list
for i in nums:
    if chunk and i < chunk[-1]:
        output.extend(chunk[::-1]) # add reversed chunk to output
        chunk[:] = [i]       # clear chunk
    else:
        chunk.append(i)      # add to chunk
output.extend(chunk[::-1])   # empty leftover chunk
print(output)

这篇关于逆序递增数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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