【问题标题】:How to get listcomprehension result as unpacked list如何将列表理解结果作为解压列表
【发布时间】:2019-06-26 11:15:30
【问题描述】:

我有一个返回集合的函数(在示例中:some_function())。我得到了一些元素的数据结构(在示例中为arr),需要将元素映射到函数,我想取回一组所有元素。不是一组集合,而是集合中所有元素的集合。我知道some_function() 只返回一维集。

我尝试使用map,但并没有完全发挥作用,我让它与列表推导一起使用,但我不太喜欢我的解决方案。

是否可以不创建列表然后解包?
或者我可以在不做太多工作的情况下以某种方式转换我从map 方法中获得的信息吗?

例子:

arr = [1, 2, 3]

# I want something like this
set.union(some_function(1), some_function(2), some_function(3))

# where some_function returns a set    

# this is my current solution
set.union(*[some_function(el) for el in arr]))

# approach with map, but I couldn't convert it back to a set
map(some_function, arr)

【问题讨论】:

    标签: python list set list-comprehension set-comprehension


    【解决方案1】:

    我认为您当前的解决方案很好。如果您想避免创建列表,您可以尝试:

    set.union(*(some_function(el) for el in arr)))
    

    【讨论】:

      【解决方案2】:

      在 Python 中,有时您不必花哨。

      result = set()
      
      for el in arr:
          result.update(some_function(el))
      

      这种方法不会创建返回值列表,因此不会保留超过必要的集合。您可以将其包装在一个函数中以保持清洁。

      【讨论】:

      • 您也可以使用functools.reduce(set.union, map(some_function, arr)) 来避免在内存中保存许多集合。如果你用像(some_function(el) for el in arr)这样的生成器表达式替换对map的调用,这也有效。
      • @chepner:这是 O(n²),因为它每次都复制集合,不是吗?
      • 嗯,可能。
      【解决方案3】:

      您可以使用生成器表达式而不是列表推导式,这样您就不必先创建临时列表:

      set.union(*(some_function(el) for el in arr)))
      

      或者,使用map

      set.union(*map(some_function, arr))
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-09-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-03-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多