开发者

How can I sort a specific range of elements in a list?

开发者 https://www.devze.com 2023-03-25 18:24 出处:网络
Suppose I have a list, lst = [5, 3, 5, 1, 4, 7] and I wa开发者_Go百科nt to get it ordered from the second element 3 to the end.

Suppose I have a list,

lst = [5, 3, 5, 1, 4, 7]

and I wa开发者_Go百科nt to get it ordered from the second element 3 to the end.

I thought I could do it by:

lst[1:].sort()

But, this doesn't work.

How can I do it?


lst = lst[0:1] + sorted(lst[1:])


lst = [5, 3, 5, 1, 4, 7]
lst[1:] = sorted(lst[1:])
print(lst) # prints [5, 1, 3, 4, 5, 7]


so = lambda x, index: x[:index]+sorted(x[index:])

so call it as so(lst, 1)

In [2]: x = [5, 3, 5, 1, 4, 7]
In [3]: so(lst, 1)
Out[4]: [5, 1, 3, 4, 5, 7]


You can use the following code:

lst = [5, 3, 5, 1, 4, 7]

searchValue = 3

def get_sorted(lVals, searchVal=None, startIndex=None):
    if startIndex and startIndex < len(lVals):
        return lVals[:startIndex] + sorted(lVals[startIndex:])         
    elif searchVal and searchVal in lVals:
        valueIndex = lst.index(searchValue)
        return lVals[:valueIndex] + sorted(lVals[valueIndex:])
    return sorted(lVals)


Its best to do it within the slice.

>>> lst = [5, 3, 5, 1, 4, 7]
>>> lst[1:]=sorted(lst[1:])
>>> lst
[5, 1, 3, 4, 5, 7]
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号