【问题标题】:Why Do I Get 'None' After Reverse() [duplicate]为什么我在 Reverse() 后得到“无” [重复]
【发布时间】:2020-12-21 17:00:36
【问题描述】:

为什么我执行此代码后得到“无”:

list_1 = ['a', 'b', 'c']

list_2 = list_1.reverse()

print(list_2)

谢谢。

【问题讨论】:

  • list_1.reverse() 是一个就地操作,这意味着它会修改现有的列表对象而不是创建一个新的对象
  • 我知道,但我不明白为什么我不能将 list_1 的新安排引用到 list_2
  • 要么不创建新列表而直接使用list_1.reverse(),要么通过list(reversed(list_1))创建新列表

标签: python


【解决方案1】:

list_1.reverse() 返回 None,但它会反转 list_1 本身。

为了得到list_1的反转结果,你应该这样做:

list_1 = ['a', 'b', 'c']

list_2 = list_1.copy()
list_2.reverse()

print(list_2)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-07-10
    • 2021-07-22
    • 1970-01-01
    • 2018-05-10
    • 2011-01-08
    • 2020-02-28
    • 2012-10-27
    • 2023-03-29
    相关资源
    最近更新 更多