许多Python的列表方法在适当的位置运行并返回None
(在我的头顶,insert
,sort
,reverse
)。
但是,有一种行为经常让我感到沮丧。如果我创建一个通常返回一个对象的新列表,并同时插入它,新列表将“消失”:
mytup = (0, 1, 2, 3, 4)
print mytup # (0, 1, 2, 3, 4)
mylist = list(mytup)
print mylist # [0, 1, 2, 3, 4]
newlist = list(mytup).insert(0, 10)
print newlist # None
因此,如果我想修改元组,则需要更多行:
newlist = list(mytup)
newlist.insert(0, 10)
print newlist # [10, 0, 1, 2, 3, 4]
所以我有两个问题:
None
的返回值?再次,列表去哪里?答案 0 :(得分:3)
insert
,sort
和reverse
就地修改列表并返回None
。在您的代码中,您实际上将返回的值存储在newlist
变量中。
newlist = list(mytup).insert(0, 10)
新创建的列表(动态创建)被垃圾收集,因为没有对它的引用。
In [151]: mytup = (0, 1, 2, 3, 4)
In [152]: lis=list(mytup) #create a new list object and add a reference to this new object
In [153]: newlist=lis.insert(0,10) #perform the insert operation on lis and store None
# in newlist
In [154]: print newlist
None
In [155]: print lis
[10, 0, 1, 2, 3, 4] #you can still access this list object with
#the help of `lis` variable.
答案 1 :(得分:1)
已经给出了第一个问题的答案;您为变量分配了最后一次函数调用的结果,即None
。以下是第二个问题的答案。
不是使用insert,而是执行以下操作:
newlist = [10] + list(mytup)
它会创建一个包含要插入的元素的新list
,将其附加到已转换的tuple
并存储(引用)生成的list
。
当然,这只有在你想要插入两端时才有效。
如果您需要将新元素插入其他位置,则必须对tuple
进行切片,例如在tuple
:
newlist = list(mytup[:3]) + [10] + list(mytup[3:])