反转具有单个元素的列表给出无 [英] Reversing a list with single element gives None

查看:67
本文介绍了反转具有单个元素的列表给出无的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I noticed odd behaviour when returning a list (with a single element) from a function and then trying to reverse it, using 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

我需要一个大人来解释创建 None 而不是 [::-1] 中看到的单个元素是怎么回事.

I need a grown-up to explain what is going on to create the None instead of the single element as seen with [::-1].

推荐答案

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

list.reverse() reverses the list in-place, but the function itself doesn't return anything.

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

这篇关于反转具有单个元素的列表给出无的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆