我有一个函数(在示例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)
您可以使用生成器表达式而不是列表推导,这样就不必首先创建临时列表:
set.union(*(some_function(el) for el in arr)))
或者,使用map
:
set.union(*map(some_function, arr))
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句