【问题标题】:why extend a python list为什么要扩展 python 列表
【发布时间】:2012-02-05 05:29:14
【问题描述】:

既然可以使用 += 运算符,为什么还要使用扩展?哪种方法最好? 另外将多个列表加入一个列表的最佳方法是什么

#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]

【问题讨论】:

    标签: python list merge append extend


    【解决方案1】:

    您可以extend() 一个带有非列表对象作为迭代器的python 列表。迭代器不存储任何值,而是一个在某些值上迭代一次的对象。更多关于迭代器here.

    在此线程中,有一些示例将迭代器用作extend() 方法的参数:append vs. extend

    【讨论】:

      【解决方案2】:

      += 只能用于将一个列表扩展为另一个列表,而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.
      

      Making a flat list out of list of lists in Python

      【讨论】:

      • 谢谢!这几乎钉了它。 _list+=list(_iterable) 是否等效?
      • 可以达到同样的效果,但底层实现会不同。
      猜你喜欢
      • 2016-12-24
      • 2014-03-30
      • 2016-01-08
      • 2013-08-02
      • 1970-01-01
      • 1970-01-01
      • 2019-09-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多