代码之家  ›  专栏  ›  技术社区  ›  Björn Pollex

python中多个列表的串联[重复]

  •  30
  • Björn Pollex  · 技术社区  · 14 年前

    这个问题已经有了答案:

    假设我有这样一个函数:

    def getNeighbors(vertex)
    

    返回与给定顶点相邻的顶点列表。现在我想创建一个列表,列出所有邻居的邻居。我是这样做的:

    listOfNeighborsNeighbors = []
    for neighborVertex in getNeighbors(vertex):
        listOfNeighborsNeighbors.append(getNeighbors(neighborsVertex))
    

    有没有比这更像蟒蛇的方法?

    7 回复  |  直到 7 年前
        1
  •  32
  •   Ignacio Vazquez-Abrams    14 年前
    [x for n in getNeighbors(vertex) for x in getNeighbors(n)]
    

    sum(getNeighbors(n) for n in getNeighbors(vertex), [])
    
        2
  •  42
  •   Jochen    14 年前

    与往常一样,itertools模块包含一个解决方案:

    >>> l1=[1, 2, 3]
    
    >>> l2=[4, 5, 6]
    
    >>> l3=[7, 8, 9]
    
    >>> import itertools
    
    >>> list(itertools.chain(l1, l2, l3))
    [1, 2, 3, 4, 5, 6, 7, 8, 9]
    
        3
  •  32
  •   Sjoerd    14 年前

    附加列表可以使用+和sum()完成:

    >>> c = [[1, 2], [3, 4]]
    >>> sum(c, [])
    [1, 2, 3, 4]
    
        4
  •  12
  •   emu    12 年前

    如果速度很重要,最好使用:

    from operator import iadd
    reduce(iadd, (getNeighbors(n) for n in getNeighbors(vertex)))
    

    这段代码的要点是通过 list.extend 列表理解会一个接一个地添加一个项目,就像调用 list.append . 这节省了一点开销,使前者(根据我的测量)快了三倍。(The iadd 操作员通常写为 += 做同样的事 扩展名 )

    使用列表理解(Ignacio的第一个解决方案)仍然是正确的方法,更容易阅读。

    但一定要避免使用 sum(..., []) 因为它是以二次方时间运行的。这是非常不切实际的 许多的 列表(超过100个左右)。

        5
  •  7
  •   Yariv    7 年前

    按速度排序:

    list_of_lists = [[x,1] for x in xrange(1000)]
    
    %timeit list(itertools.chain(*list_of_lists))
    100000 loops, best of 3: 14.6 µs per loop
    
    %timeit list(itertools.chain.from_iterable(list_of_lists))
    10000 loops, best of 3: 60.2 µs per loop
    
    min(timeit.repeat("ll=[];\nfor l in list_of_lists:\n ll.extend(l)", "list_of_lists=[[x,1] for x in xrange(1000)]",repeat=3, number=100))/100.0
    9.620904922485351e-05
    
    %timeit [y for z in list_of_lists for y in z]
    10000 loops, best of 3: 108 µs per loop
    
    %timeit sum(list_of_lists, [])
    100 loops, best of 3: 3.7 ms per loop
    
        6
  •  2
  •   renadeen    9 年前

    我喜欢 itertools.chain 方法是因为它以线性时间运行(sum(…)以qudratic时间运行),但@jochen没有显示如何处理动态长度列表。这是OP问题的解决方案。

    import itertools
    list(itertools.chain(*[getNeighbors(n) for n in getNeighbors(vertex)]))
    

    你可以摆脱 list(...) 如果iterable对您足够,则调用。

        7
  •  0
  •   realmaniek    7 年前

    使用 扩展() (就地更新)结合使用reduce而不是 () (每次都有新对象)应该更有效,但是我太懒了,无法测试它:)

    mylist = [[1,2], [3,4], [5,6]] 
    reduce(lambda acc_l, sl: acc_l.extend(sl) or acc_l, mylist)