逆序递增数字

时间:2019-01-02 18:54:06

标签: python list numpy sorting

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

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

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

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

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

因此,对于以下列表:

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]     

2 个答案:

答案 0 :(得分:0)

尝试一下:

(带有@Scott Boston和@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)

答案 1 :(得分:0)

带有理解列表:

profileImage