python基础-列表sort妙用

我相信每个人在使用列表时都使用过排序或排序函数,所以请再次查看它。

[En]

I believe everyone has used the sort or sorted function when using the list, so review it again.

sort语法:

应该注意的是,它直接在原始列表上排序,并作为None返回

[En]

It should be noted that it is sorted directly on the original list and returned as None

另一个密钥的用法如下:

[En]

The use of another key is as follows:

具体情况如下:

[En]

As follows:

结果如下:

[En]

The results are as follows:

因此,问题来了

[En]

So, * here comes the problem * :

要求如下:按年龄倒序排序,如果年龄相同,则按姓名的字母ASCII排序。

[En]

The requirements are as follows: sort by age in reverse order, and then sort by the letter ASCII of name if the age is the same.

怎么做,我们需要考虑两点。这里有两个排序,看看Sort是否支持它。

[En]

What to do, we need to consider two points. Here are two sorts to see if sort supports it.

让我们试一试。

[En]

Let’s have a try.

重新定义数据:

[En]

Redefine the data:

结果如下:

[En]

The results are as follows:

是!

[En]

Yes!

但是:我们需求是age逆序排序,age相同情况下,按名字排序。在查看相关文档后,发现reverse不能放在key内部….

解决办法:这个时候,我们可以换个角度思考,年龄是正数,为什么不把年龄排序成负数,反过来就是正序,不能只解决问题。

[En]

Solution: at this time, we can think differently, age is a positive number, why don’t we sort the age into a negative number, reverse is a positive order, can not just solve the problem.

具体情况如下:

[En]

As follows:

结果:

[En]

Results:

很好。解决这个问题。一个小减号。您不必自己重写排序。

[En]

Fine. Solve the problem. A small minus sign. You don’t have to rewrite sort yourself.

Original: https://www.cnblogs.com/landhu/p/15562404.html
Author: Believer007
Title: python基础-列表sort妙用

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/6569/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

免费咨询
免费咨询
扫码关注
扫码关注
联系站长

站长Johngo!

大数据和算法重度研究者!

持续产出大数据、算法、LeetCode干货,以及业界好资源!

2022012703491714

微信来撩,免费咨询:xiaozhu_tec

分享本页
返回顶部