字符串列表按字符长度排序

看一下例子,

>>> list = ['tom','jan','marry','coco']
>>> list
['tom', 'jan', 'marry', 'coco']

对list进行默认排序
>>> list.sort()
>>> list
['coco', 'jan', 'marry', 'tom']

这时我们可以看到,默认的顺序是英文字母顺序,我们可以指定key来解决字符串长度排序的问题,解决方法如下:
>>> list.sort(key=lambda x:len(x))
>>> list
['jan', 'tom', 'coco', 'marry']

猜你喜欢

转载自blog.csdn.net/qq_19340683/article/details/72236928