Why does the following code give 'None'? How can I resolve this?
为什么以下代码给出“无”?我该如何解决这个问题?
def f1(list1):
f2(list1.append(2))
def f2(list1):
print(list1)
f1([1])
What also doesn't work:
什么也行不通:
def f1(list1):
arg1 = list1.append(2)
f2(arg1)
2 个解决方案
#1
6
It depends on what you want to do. If you want list1
to have changed after a call to f1
, use
这取决于你想做什么。如果您希望在调用f1后更改list1,请使用
def f1(list1):
list1.append(2)
f2(list1)
See what happens:
走着瞧吧:
>>> l = [1]
>>> f1(l) # Modifies l in-place!
[1, 2]
>>> l
[1, 2]
If you don't want list1
to be changed:
如果您不想更改list1:
def f1(list1):
f2(list1 + [2])
Now see this:
现在看到这个:
>>> l = [1]
>>> f1(l) # Leaves l alone!
[1, 2]
>>> l
[1]
#2
7
In general, Python methods that mutate an object (such as list.append
, list.extend
, or list.sort
) return None
.
通常,改变对象的Python方法(例如list.append,list.extend或list.sort)将返回None。
If you wish to print out the new list:
如果您想打印新列表:
def f1(list1):
list1.append(2)
f2(list1)
#1
6
It depends on what you want to do. If you want list1
to have changed after a call to f1
, use
这取决于你想做什么。如果您希望在调用f1后更改list1,请使用
def f1(list1):
list1.append(2)
f2(list1)
See what happens:
走着瞧吧:
>>> l = [1]
>>> f1(l) # Modifies l in-place!
[1, 2]
>>> l
[1, 2]
If you don't want list1
to be changed:
如果您不想更改list1:
def f1(list1):
f2(list1 + [2])
Now see this:
现在看到这个:
>>> l = [1]
>>> f1(l) # Leaves l alone!
[1, 2]
>>> l
[1]
#2
7
In general, Python methods that mutate an object (such as list.append
, list.extend
, or list.sort
) return None
.
通常,改变对象的Python方法(例如list.append,list.extend或list.sort)将返回None。
If you wish to print out the new list:
如果您想打印新列表:
def f1(list1):
list1.append(2)
f2(list1)