根据字符串长度对Python列表进行排序

问题:根据字符串长度对Python列表进行排序

我想根据字符串长度对字符串列表进行排序。我尝试使用sort,如下所示,但似乎无法给我正确的结果。

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']

可能是什么问题?

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?


回答 0

将传递lambda给时sort,您需要返回一个整数,而不是布尔值。因此,您的代码应改为:

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

请注意,cmp是一个内置函数,cmp(x, y)如果x小于则返回-1 yx等于则返回0 yx大于则返回1 y

当然,您可以改为使用key参数:

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

这告诉该sort方法根据键函数返回的值进行排序。

编辑:感谢下面的balpha和Ruslan指出您可以len直接将其作为关键参数传递给函数,从而消除了对a的需要lambda

xs.sort(key=len)

正如Ruslan在下面指出的那样,您还可以使用内置的排序函数而不是list.sort方法,该方法创建一个新列表,而不是就地对现有列表进行排序:

print(sorted(xs, key=len))

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))

This tells the sort method to order based on whatever the key function returns.

EDIT: Thanks to balpha and Ruslan below for pointing out that you can just pass len directly as the key parameter to the function, thus eliminating the need for a lambda:

xs.sort(key=len)

And as Ruslan points out below, you can also use the built-in sorted function rather than the list.sort method, which creates a new list rather than sorting the existing one in-place:

print(sorted(xs, key=len))

回答 1

与Eli的答案相同-只是使用较短的表格,因为您可以lambda在此处跳过一部分。

创建新列表:

>>> xs = ['dddd','a','bb','ccc']
>>> sorted(xs, key=len)
['a', 'bb', 'ccc', 'dddd']

就地排序:

>>> xs.sort(key=len)
>>> xs
['a', 'bb', 'ccc', 'dddd']

The same as in Eli’s answer – just using a shorter form, because you can skip a lambda part here.

Creating new list:

>>> xs = ['dddd','a','bb','ccc']
>>> sorted(xs, key=len)
['a', 'bb', 'ccc', 'dddd']

In-place sorting:

>>> xs.sort(key=len)
>>> xs
['a', 'bb', 'ccc', 'dddd']

回答 2

我想添加排序时pythonic键函数的工作方式:

装饰-排序-非装饰设计模式:

当使用所谓的decorate-sort-undecorate设计模式实现排序时,Python对关键功能的支持。

它分3个步骤进行:

  1. 列表中的每个元素都会临时替换为“修饰的”版本,其中包含应用于该元素的键函数的结果。

  2. 该列表是根据键的自然顺序排序的。

  3. 装饰元素将替换为原始元素。

用于在进行比较之前在每个列表元素上指定要调用的函数的关键参数。docs

I Would like to add how the pythonic key function works while sorting :

Decorate-Sort-Undecorate Design Pattern :

Python’s support for a key function when sorting is implemented using what is known as the decorate-sort-undecorate design pattern.

It proceeds in 3 steps:

  1. Each element of the list is temporarily replaced with a “decorated” version that includes the result of the key function applied to the element.

  2. The list is sorted based upon the natural order of the keys.

  3. The decorated elements are replaced by the original elements.

Key parameter to specify a function to be called on each list element prior to making comparisons. docs


回答 3

最简单的方法是:

list.sort(key = lambda x:len(x))

The easiest way to do this is:

list.sort(key = lambda x:len(x))


回答 4

编写一个功能Lensort以根据长度对字符串列表进行排序。

def lensort(a):
    n = len(a)
    for i in range(n):
        for j in range(i+1,n):
            if len(a[i]) > len(a[j]):
                temp = a[i]
                a[i] = a[j]
                a[j] = temp
    return a
print lensort(["hello","bye","good"])

Write a function lensort to sort a list of strings based on length.

def lensort(a):
    n = len(a)
    for i in range(n):
        for j in range(i+1,n):
            if len(a[i]) > len(a[j]):
                temp = a[i]
                a[i] = a[j]
                a[j] = temp
    return a
print lensort(["hello","bye","good"])

回答 5

def lensort(list_1):
    list_2=[];list_3=[]
for i in list_1:
    list_2.append([i,len(i)])
list_2.sort(key = lambda x : x[1])
for i in list_2:
    list_3.append(i[0])
return list_3

这对我有用!

def lensort(list_1):
    list_2=[];list_3=[]
for i in list_1:
    list_2.append([i,len(i)])
list_2.sort(key = lambda x : x[1])
for i in list_2:
    list_3.append(i[0])
return list_3

This works for me!


回答 6

我可以使用以下两种方法来实现

def lensort(x):
    list1 = []
    for i in x:
        list1.append([len(i),i])
    return sorted(list1)

lista = ['a', 'bb', 'ccc', 'dddd']
a=lensort(lista)
print([l[1] for l in a])

在使用Lambda的一个Liner中,如下所示,上面已经给出了答案。

 lista = ['a', 'bb', 'ccc', 'dddd']
 lista.sort(key = lambda x:len(x))
 print(lista)

I can do it using below two methods, using function

def lensort(x):
    list1 = []
    for i in x:
        list1.append([len(i),i])
    return sorted(list1)

lista = ['a', 'bb', 'ccc', 'dddd']
a=lensort(lista)
print([l[1] for l in a])

In one Liner using Lambda, as below, a already answered above.

 lista = ['a', 'bb', 'ccc', 'dddd']
 lista.sort(key = lambda x:len(x))
 print(lista)