3 回答

TA貢獻(xiàn)1883條經(jīng)驗(yàn) 獲得超3個(gè)贊
字節(jié)碼級(jí)別的唯一區(qū)別在于,這種.extend方式涉及函數(shù)調(diào)用,這在Python中略高于INPLACE_ADD。
除非你執(zhí)行這項(xiàng)行動(dòng)數(shù)十億次,否則你應(yīng)該擔(dān)心的事情真的沒什么。但是,瓶頸可能會(huì)出現(xiàn)在其他地方。

TA貢獻(xiàn)1895條經(jīng)驗(yàn) 獲得超7個(gè)贊
您不能將+ =用于非局部變量(對于函數(shù)而言不是局部的變量,也不是全局變量)
def main():
l = [1, 2, 3]
def foo():
l.extend([4])
def boo():
l += [5]
foo()
print l
boo() # this will fail
main()
這是因?yàn)閷τ跀U(kuò)展案例編譯器將l使用LOAD_DEREF指令加載變量,但對于+ =它將使用LOAD_FAST- 并且你得到*UnboundLocalError: local variable 'l' referenced before assignment*

TA貢獻(xiàn)1869條經(jīng)驗(yàn) 獲得超4個(gè)贊
你可以鏈接函數(shù)調(diào)用,但你不能直接+ =函數(shù)調(diào)用:
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
添加回答
舉報(bào)