<分区>
为什么这样做 -
a = []
a.append(4)
print a
但这不——
print [].append(4)
第二种情况的输出是None
。你能解释一下输出吗?
标签 python
<分区>
为什么这样做 -
a = []
a.append(4)
print a
但这不——
print [].append(4)
第二种情况的输出是None
。你能解释一下输出吗?
最佳答案
append
方法没有返回值。它就地更改了列表,并且由于您没有将 []
分配给任何变量,所以它只是“迷失在空间中”
class FluentList(list):
def append(self, value):
super(FluentList,self).append(value)
return self
def extend(self, iterable):
super(FluentList,self).extend(iterable)
return self
def remove(self, value):
super(FluentList,self).remove(value)
return self
def insert(self, index, value):
super(FluentList,self).insert(index, value)
return self
def reverse(self):
super(FluentList,self).reverse()
return self
def sort(self, cmp=None, key=None, reverse=False):
super(FluentList,self).sort(cmp, key, reverse)
return self
li = FluentList()
li.extend([1,4,6]).remove(4).append(7).insert(1,10).reverse().sort(key=lambda x:x%2)
print li
我没有重载所有有问题的方法,但概念应该很清楚。
关于python - 为什么 [].append() 在 python 中不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14265589/