我是靠谱客的博主 震动小懒虫,最近开发中收集的这篇文章主要介绍python按照字符串长度排序,根据字符串的长度对Python列表进行排序,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

I want to sort a list of strings based on the string length. I tried to use sort as follows, but it doesn't seem to give me correct result.

xs = ['dddd','a','bb','ccc']

print xs

xs.sort(lambda x,y: len(x) < len(y))

print xs

['dddd', 'a', 'bb', 'ccc']

['dddd', 'a', 'bb', 'ccc']

What might be wrong?

解决方案

When you pass a lambda to sort, you need to return an integer, not a boolean. So your code should instead read as follows:

xs.sort(lambda x,y: cmp(len(x), len(y)))

Note that cmp is a builtin function such that cmp(x, y) returns -1 if x is less than y, 0 if x is equal to y, and 1 if x is greater than y.

Of course, you can instead use the key parameter:

xs.sort(key = lambda s: len(s))</

最后

以上就是震动小懒虫为你收集整理的python按照字符串长度排序,根据字符串的长度对Python列表进行排序的全部内容,希望文章能够帮你解决python按照字符串长度排序,根据字符串的长度对Python列表进行排序所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(35)

评论列表共有 0 条评论

立即
投稿
返回
顶部