3 回答
TA贡献1883条经验 获得超3个赞
字节码级别的唯一区别在于,这种.extend方式涉及函数调用,这在Python中略高于INPLACE_ADD。
除非你执行这项行动数十亿次,否则你应该担心的事情真的没什么。但是,瓶颈可能会出现在其他地方。
TA贡献1895条经验 获得超7个赞
您不能将+ =用于非局部变量(对于函数而言不是局部的变量,也不是全局变量)
def main():
l = [1, 2, 3]
def foo():
l.extend([4])
def boo():
l += [5]
foo()
print l
boo() # this will fail
main()
这是因为对于扩展案例编译器将l使用LOAD_DEREF指令加载变量,但对于+ =它将使用LOAD_FAST- 并且你得到*UnboundLocalError: local variable 'l' referenced before assignment*
TA贡献1869条经验 获得超4个赞
你可以链接函数调用,但你不能直接+ =函数调用:
class A:
def __init__(self):
self.listFoo = [1, 2]
self.listBar = [3, 4]
def get_list(self, which):
if which == "Foo":
return self.listFoo
return self.listBar
a = A()
other_list = [5, 6]
a.get_list("Foo").extend(other_list)
a.get_list("Foo") += other_list #SyntaxError: can't assign to function call
添加回答
举报