【问题标题】:Why isn't .reverse() working?为什么 .reverse() 不起作用?
【发布时间】:2017-11-15 06:38:42
【问题描述】:

我正在尝试提取一个句子并拆分该句子,将其反转,然后将其打印到屏幕上。

我无法理解.reverse() 的工作原理? 当我做类似的事情时:

test = ['This','is','a','test']
new_test = test.reverse()
print(new_test)

当我运行它时,我得到None,这是为什么呢?我怎样才能使.reverse() 工作?

这是我的最终代码:

sentence = input("What is your sentence? ")
split_sentence = sentence.split().reverse()
for word in sentence:
    print(word,end='')

【问题讨论】:

    标签: python list reverse


    【解决方案1】:

    reverse() 在原地运行,并且不返回新数组。如果要使用副本,则需要执行以下操作:

    arr = [1, 2, 3, 4, 5]
    copy = arr.copy() # omit this if you don't want a new list
    copy.reverse()
    # copy now contains [5, 4, 3, 2, 1]
    # arr still contains [1, 2, 3, 4, 5]
    

    【讨论】:

    • 有趣的是为什么 python 让它像这样“就地”运行?似乎更令人困惑。
    • 最终归结为倒转列表在 C 中的实现方式,这很简单。
    【解决方案2】:

    reverse() 就地反转列表,并返回None。只需打印您的原始列表:

    test = ['This','is','a','test']
    test.reverse() # In-place!
    print(test)
    

    【讨论】:

    • 有趣的是为什么 python 让它像这样“就地”运行?似乎更令人困惑。
    【解决方案3】:

    您可以使用slicing

    test = ['This','is','a','test']
    >>> print(test[::-1])
    ['test', 'a', 'is', 'This']
    

    【讨论】:

      【解决方案4】:

      reverse() 函数执行列表的就地反转,这就是您在new_test 列表中获得None 的原因。您可以使用以下 sn-p 来反转列表。

      from copy import deepcopy
      
      test = ['This','is','a','test']
      new_test = deepcopy(test)
      print(new_test)
      new_test.reverse()
      print(new_test)
      

      输出:

      ['This', 'is', 'a', 'test']
      ['test', 'a', 'is', 'This']
      

      【讨论】:

        【解决方案5】:
        list1 = [1,2,3,4,5,6]
        print([ele for ele in reversed(list1)])
        

        输出:

        [6,5,4,3,2,1]
        

        【讨论】:

          猜你喜欢
          • 2011-06-08
          • 1970-01-01
          • 2021-04-10
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-11-25
          • 2013-05-03
          • 1970-01-01
          相关资源
          最近更新 更多