Sorting a list in python from the second element on

心已入冬 提交于 2021-02-07 19:18:05

问题


I want to sort a list but I want it to be sorted excluding the first element.

For example:

a = ['T', 4, 2, 1, 3]

Now I want the list to be sorted but the first element should stay in its place:

a = ['T', 1, 2, 3, 4]

I know this can be done by using a sorting algorithm but is there a one line way to do it or a more pythonic way to do this?


回答1:


You could slice it, sort the trailing slice and concatenate it afterwards:

>>> a = a[:1] + sorted(a[1:])
>>> a
['T', 1, 2, 3, 4]



回答2:


You can do so by slice assignment where you replace a slice of a with a sorted slice of a:

>>> a = ['T',4,2,1,3]
>>> a[1:] = sorted(a[1:])
>>> a
['T', 1, 2, 3, 4]


来源:https://stackoverflow.com/questions/43770650/sorting-a-list-in-python-from-the-second-element-on

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!