为什么要扩展Python列表

7 投票
2 回答
1258 浏览
提问于 2025-04-17 09:46

为什么要用extend方法,而直接用+=操作符不行吗?哪种方法更好?还有,把多个列表合并成一个列表的最佳方式是什么?

#my prefered way
_list=[1,2,3]
_list+=[4,5,6]
print _list
#[1, 2, 3, 4, 5, 6]

#why use extend:
_list=[1,2,3]
_list.extend([4,5,6])
print _list
#[1, 2, 3, 4, 5, 6]



_lists=[range(3*i,3*i+3) for i in range(3)]
#[[0, 1, 2], [3, 4, 5], [6, 7, 8]]

#my prefered way of merging lists
print sum(_lists,[])
#[0, 1, 2, 3, 4, 5, 6, 7, 8]


#is there a better way?
from itertools import chain
print list(chain(*_lists))
#[0, 1, 2, 3, 4, 5, 6, 7, 8]

2 个回答

1

你可以用一个非列表的对象来扩展(`extend()`)一个Python列表,这个非列表的对象需要是一个迭代器。迭代器并不存储任何值,它只是一个可以一次性遍历某些值的对象。想了解更多关于迭代器的内容,可以点击这里

在这个讨论中,有一些例子展示了如何将迭代器作为`extend()`方法的参数使用:append与extend的区别

16

+= 只能用来把一个列表扩展成另一个列表,而 extend 可以用来把一个列表扩展成一个可迭代对象

比如,你可以这样做:

a = [1,2,3]
a.extend(set([4,5,6]))

但你不能这样做:

a = [1,2,3]
a += set([4,5,6])

关于第二个问题,

[item for sublist in l for item in sublist] is faster.

可以参考 如何将列表中的列表变成一个扁平的列表

撰写回答