我不知道为什么该代码的结果为零



我不知道为什么该代码的结果为NONE:

s = [1,1,2,3,4,5]
b=s.remove(1)
print(b)

现在,没关系。

s = [1,1,2,3,4,5]
s.remove(1)
print(s)

告诉我为什么如此不同。

remove() 方法仅从列表中删除给定的元素。

它不返回任何值。

remove()不返回任何值意味着b正在None。您可以使用pop()来获取返回值,而不是remove(),如下所示:

s = [1,1,2,3,4,5]
b=s.pop(1)   # Here `remove()` returns `None`, hence the value of `b` is `None`. 
print(b)
s = [1,1,2,3,4,5]
s.remove(1)
print(s)

我希望它能帮助你。

最新更新