【问题标题】:Is there a version of list.sort() that returns the sorted list?是否有返回排序列表的 list.sort() 版本?
【发布时间】:2012-03-14 06:00:22
【问题描述】:

我正在尝试执行内联操作,在该操作中我需要对列表进行排序作为流程的一部分。 list 类型对象的 sort 函数对调用它的列表进行操作,而不是返回结果。

Python docs 证实了这一点:

list.sort()
对列表中的项目进行适当的排序。

我通过 Python 命令行尝试过,结果如下:

>>> a = list("hello").sort()
>>> print a
None
>>> b = list("hello")
>>> print b
['h', 'e', 'l', 'l', 'o']
>>> b.sort()
>>> print b
['e', 'h', 'l', 'l', 'o']

有没有办法绕过这个问题,使如下一行成为可能?

result = list(random.choice(basesalts)).sort()

使用上面的代码可以帮助我减少代码的长度和冗长。

【问题讨论】:

  • “似乎在它被调用的列表上运行”。那是错误的。它没有“似乎”。它是这样定义的。没有例外。这就是它应该工作的方式。 list.sort() 不返回值;它修改列表。 result= ....sort() 永远无法工作。根据定义。
  • "似乎证实了这一点:" 错了。他们实际上证实了这一点。

标签: python list sorting random shuffle


【解决方案1】:

有内置的sorted()

>>> a = sorted(list('hello'))
>>> a
['e', 'h', 'l', 'l', 'o']

另外请注意,您不再需要 list()

>>> sorted('hello')
['e', 'h', 'l', 'l', 'o']

由于basesalts 似乎是一个字符串列表,您可以这样做:

result = sorted(random.choice(basesalts))

如果那是您正在寻找的那种输出。

【讨论】:

  • sorted(foo) 本质上是temp = list(foo); temp.sort(); return temp,从技术上讲,在将字符串传递给sorted() 之前无需将其转换为列表。 :-)
【解决方案2】:

使用sorted

它从可迭代的项目中返回一个新的排序列表。

>>> a = sorted(list('hello'))
>>> a
['e', 'h', 'l', 'l', 'o']
>>>

不同之处在于 list.sort() 方法只为列表定义。相比之下, sorted() 函数接受任何可迭代对象。

所以,你可以这样做

>>> a = sorted('hello')
>>> a
['e', 'h', 'l', 'l', 'o']
>>>

看看这篇不错的文章Sorting Mini-HOW TO

【讨论】:

    【解决方案3】:

    Sorted 是您的朋友。它不是列表类的成员函数,它是一个将列表作为参数的内置函数。

    类列表没有排序功能。

    list1 = [ 1, 4, 5, 2]
    print sorted(list1)
    
    >> [1, 2, 4, 5]
    

    【讨论】:

      猜你喜欢
      • 2011-11-10
      • 1970-01-01
      • 2023-01-30
      • 1970-01-01
      • 1970-01-01
      • 2016-03-19
      相关资源
      最近更新 更多