【问题标题】:Sort all lists within a list [duplicate]对列表中的所有列表进行排序[重复]
【发布时间】:2021-12-24 06:57:37
【问题描述】:

如果您有一个列表,例如:

lst = [[8, 4], [10,2]]

你如何排序它使得 lst 是:

lst = [[4, 8], [2,10]]

我试过了:

lst = [i.sort() for i in lst]

和:

lst = list(map(lambda x: x.sort(), lst))

但是这些只是返回一个没有 None 的列表。

任何帮助将不胜感激!

【问题讨论】:

  • i.sort() 返回None 并对列表进行适当的排序。请改用sorted(i)

标签: python list sorting


【解决方案1】:

i.sort() 对列表进行就地排序并返回None。相反,你使用sorted():

lst = [sorted(i) for i in lst]

或者一个for循环:

for i in lst:
    i.sort()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-11-14
    • 1970-01-01
    • 2015-09-21
    • 2021-02-09
    • 2013-08-11
    • 2014-10-27
    • 2019-07-01
    相关资源
    最近更新 更多