从python的第二个元素开始对列表进行排序 [英] Sorting a list in python from the second element on

查看:74
本文介绍了从python的第二个元素开始对列表进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想对列表进行排序,但我希望对列表进行排序(不包括第一个元素).

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

例如:

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]

我知道这可以通过使用排序算法来完成,但是有没有一种单行的方式可以做到这一点,或者有更多的 pythonic 方式可以做到这一点?

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?

推荐答案

您可以通过切片分配来实现,您可以将 a 的切片替换为 a :

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]

这篇关于从python的第二个元素开始对列表进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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