【问题标题】:Why That Code Returns 'None' (Tuples in List) [duplicate]为什么该代码返回“无”(列表中的元组)[重复]
【发布时间】:2022-02-02 05:39:43
【问题描述】:
posts = []
rows = [('02.02', 'title2', 'text2', 15, 1), ('01.02', 'title', 'text', 16, 1)]
rows = rows.sort(key=lambda x:x[3])
for i in range(2):
     posts.append(rows[i])
print(posts)

为什么该代码返回None,我该如何解决?

【问题讨论】:

  • 作为关于.sort() 为何“就地”工作的背景知识,请对 mutableimmutable 进行一些研究Python中的对象;其中list 是可变的。
  • 题外话,但你不需要那个for循环,只需要posts.extend(rows[:2]),或者甚至去掉posts = [],只需要posts = rows[:2]

标签: python list sorting


【解决方案1】:

代替

rows = rows.sort(key=lambda x:x[3])

你想要:

rows.sort(key=lambda x:x[3])

因为.sort() 会自动更新rows 而无需像这样重新分配:

posts = []
rows = [('02.02', 'title2', 'text2', 15, 1), ('01.02', 'title', 'text', 16, 1)]
rows.sort(key=lambda x:x[3]) #notice the change here
for i in range(2):
     posts.append(rows[i])
print(posts)

输出:

[('02.02', 'title2', 'text2', 15, 1), ('01.02', 'title', 'text', 16, 1)]

.sort() 函数更新行,但返回 None

【讨论】:

  • 呃……确实如此。谢谢你帮助我。 :)
猜你喜欢
  • 2021-04-15
  • 1970-01-01
  • 2020-03-10
  • 1970-01-01
  • 1970-01-01
  • 2017-06-29
  • 1970-01-01
  • 2018-12-18
  • 2019-02-20
相关资源
最近更新 更多