【问题标题】:Python .sort() on a list of a set returns None [duplicate]集合列表上的Python .sort()返回无[重复]
【发布时间】:2017-12-16 06:51:11
【问题描述】:

Python 3.6

刚遇到这个问题(如下),添加.sort() 导致我的表达式返回无。

这应该有效吗?如果不是,为什么不呢?

>>> x = [1,2,3,3,45,5,6,6,7,7]
>>> y = [3,4,34,643,6,234,3,34,5,22,3]
>>> w =[x,y]
>>> x = [set(i) for i in w]
>>> x
[{1, 2, 3, 5, 6, 7, 45}, {34, 3, 4, 643, 6, 5, 234, 22}]
>>> common_elements = list(set.union(*x))
>>> common_elements
[1, 2, 3, 34, 5, 6, 7, 4, 643, 234, 45, 22]
>>> common_elements = list(set.union(*x)).sort() #Adding .sort() returns None
>>> common_elements
>>>                #Nothing, None

【问题讨论】:

  • 对不起伙计,太快了,我看不出来!

标签: python sorting set union


【解决方案1】:

是的,list.sort 方法对列表进行就地排序并返回None。如果要返回排序后的列表,请使用sorted 方法。

>>> lst=[5, 2, 1, 4, 3]
>>> lst.sort()
>>> lst
[1, 2, 3, 4, 5]
>>> lst=[5, 2, 1, 4, 3]
>>> lst=sorted(lst)
>>> lst
[1, 2, 3, 4, 5]
>>> 

所以你必须使用:common_elements = sorted(list(set.union(*x))) 或者你可以像这样就地排序:

common_elements = list(set.union(*x))
common_elements.sort()

【讨论】:

  • 看起来很明显,当你这样说的时候。我认为它会返回排序列表......在将其排序到位后。谢谢!
  • @JamesSchinner 请注意,内置函数 sorted() 确实返回了一个新列表。
  • 我意识到,我对“就地”的理解并不完全正确。我似乎认为这意味着“在与该数据相同的内存位置对数据进行排序”,但更好的解释是“在与该数据相同的内存位置对数据进行排序并返回 None”
【解决方案2】:

sort 已就位。它进行排序并且不返回值。

l = list((4,3,2,1))
l
# OUTPUT
# [4, 3, 2, 1]
l.sort()
l
# OUTPUT
# [1, 2, 3, 4]

【讨论】:

    【解决方案3】:

    你必须对集合使用 sorted 方法:

    common_elements = list(sorted(set.union(*x)))
    

    排序方法是就地的,它不会返回任何东西,另一个选项是

    common_elements = list(set.union(*x))
    common_elements.sort()
    

    【讨论】:

      【解决方案4】:

      调用 .sort() 时不要重新分配 common_elements。 .sort() 就地修改列表并返回 None。

      【讨论】:

        猜你喜欢
        • 2019-06-01
        • 2011-02-05
        • 2016-01-15
        • 1970-01-01
        • 2014-04-11
        • 2019-02-01
        • 2016-06-30
        • 2015-07-11
        相关资源
        最近更新 更多