【问题标题】:Generator expression calling a function that returns lists [duplicate]生成器表达式调用返回列表的函数[重复]
【发布时间】:2013-06-17 00:59:57
【问题描述】:

我有一个返回列表的函数,我想在使用紧凑的生成器表达式(或任何不错且紧凑的方法)在列表上调用该函数时合并该函数的输出

假设我有一个def foo(bar):,其中 bar 是整数,它在经过一些疯狂的复杂计算后返回一个列表。

foo(1)=[9,1,5]
foo(2)=[1]
foo(3)=[7,1]

arr=[1,2,3]

如何在一行代码之后获得arr=[9,1,5,1,7,1]

arr=[foo(x) for x in arr] 给了我[[9,1,5],[1],[7,1]]
我不想再写一行来展开列表中的列表。

【问题讨论】:

    标签: python generator-expression


    【解决方案1】:
    from itertools import chain
    result = list(chain.from_iterable(foo(x) for x in arr))
    

    【讨论】:

      猜你喜欢
      • 2021-04-07
      • 1970-01-01
      • 2010-12-09
      • 2012-01-19
      • 2018-09-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-23
      • 1970-01-01
      相关资源
      最近更新 更多