问题
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