守着星空守着你
對于您的情況,唯一的差別是性能:追加速度是其兩倍。Python 3.0 (r30:67507, Dec 3 2008, 20:14:27) [MSC v.1500 32 bit (Intel)] on win32Type "help", "copyright", "credits" or "license" for more information.>>> import timeit>>> timeit.Timer('s.append("something")', 's = []').timeit()0.20177424499999999>>> timeit.Timer('s += ["something"]', 's = []').timeit()0.41192320500000079Python 2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC v.1310 32 bit (Intel)] on win32Type "help", "copyright", "credits" or "license" for more information.>>> import timeit>>> timeit.Timer('s.append("something")', 's = []').timeit()0.23079359499999999>>> timeit.Timer('s += ["something"]', 's = []').timeit()0.44208112500000141一般情況下,append将向清單中添加一個項目,同時+=将右側清單的所有元素複制到左側清單中。更新:性能分析比較位元組碼我們可以假設append版本浪費在LOAD_ATTR+中的循環CALL_FUNCTION,+ =版本 - 在BUILD_LIST。顯然BUILD_LIST勝過LOAD_ATTR+ CALL_FUNCTION。>>> import dis>>> dis.dis(compile("s = []; s.append('spam')", '', 'exec')) 1 0 BUILD_LIST 0 3 STORE_NAME 0 (s) 6 LOAD_NAME 0 (s) 9 LOAD_ATTR 1 (append) 12 LOAD_CONST 0 ('spam') 15 CALL_FUNCTION 1 18 POP_TOP 19 LOAD_CONST 1 (None) 22 RETURN_VALUE>>> dis.dis(compile("s = []; s += ['spam']", '', 'exec')) 1 0 BUILD_LIST 0 3 STORE_NAME 0 (s) 6 LOAD_NAME 0 (s) 9 LOAD_CONST 0 ('spam') 12 BUILD_LIST 1 15 INPLACE_ADD 16 STORE_NAME 0 (s) 19 LOAD_CONST 1 (None) 22 RETURN_VALUE我們可以通過消除LOAD_ATTR開銷來進一步提高性能:>>> timeit.Timer('a("something")', 's = []; a = s.append').timeit()0.15924410999923566