python中sort用法

2025-10-06 06:13:53

1、sort是用来排序列表的。

a=[3,1,2]

a.sort()

print(a)

给出列表a的元素排序,默认的是从小到大排列。

python中sort用法

2、a.sort(reverse=True)则是反向排序,从大到小排列。

python中sort用法

3、字母之间也存在先后顺序:

a=['a','c','b']

a.sort()

python中sort用法

4、大写字母排在小写字母前面:

a=['a','A','b','B','c','C']

python中sort用法

5、数字变成的字符串,排在大写字母前面:

a=['1','12','123',

   'a','A','b',

   'B','c','C']

python中sort用法

6、英文的标点符号,排在数字型字符串前面:

a=[',','.','aBC',

   '1','12','123',

   'a','A','b',

   'B','c','C']

python中sort用法

7、中文的标点符号,排在英文字母后面,而且句号排在逗号前面:

a=[',','.',',','。',

   '1','12','123',

   'a','A','b',

   'B','c','C']

python中sort用法

8、列表里面如果即有数字(非字符串形式的数字),又有字符串,则无法排序。

原因是:

'<' not supported between instances of 'int' and 'str';

无法比较数字和字符串的大小。

python中sort用法

声明:本网站引用、摘录或转载内容仅供网站访问者交流或参考,不代表本站立场,如存在版权或非法内容,请联系站长删除,联系邮箱:site.kefu@qq.com。
相关推荐
  • 阅读量:159
  • 阅读量:124
  • 阅读量:33
  • 阅读量:41
  • 阅读量:36
  • 猜你喜欢