代码之家  ›  专栏  ›  技术社区  ›  Ghoul Fool

用一个元素反转一个列表就不会有[重复]

  •  0
  • Ghoul Fool  · 技术社区  · 6 年前

    我注意到从一个函数返回一个列表(包含一个元素),然后尝试使用reverse()反转它时出现了奇怪的行为

    我在这里提炼出来:

    def myFunction():
      return ["The Smiths"]
    
    nums = [5,4,3,2,1]
    nums.reverse()
    print nums # 1,2,3,4,5 - fine!
    
    # lets use one element in a list
    something = ["Gwen Stefani"]
    something.reverse()
    print something # ["Gwen Stefani"] also fine
    
    # now let's do the same, but from a function
    a = myFunction()
    print a # The Smiths
    print a.reverse() # None
    print a[::-1] # The Smiths
    

    1 回复  |  直到 6 年前
        1
  •  2
  •   iBug    6 年前

    list.reverse() 就地反转列表,但函数本身不返回任何内容。

    a = ["The Smiths"]
    print a # The Smiths
    print a.reverse() # None
    print a # It's already there