python - 使用 map-reduce/itertools 对嵌套迭代求和

标签 python python-3.x functional-programming mapreduce python-itertools

我已经被这个数据结构困扰了一段时间了:

iter([iter([1,0]),iter([1,1]),iter([0,0])])

我想使用 map-reduce/itertools 计算最内部元素的总和。

我能够使用 for 循环相当快地得到答案:

outer_iter = iter([iter([1,0]),iter([1,1]),iter([0,0])])

for inner_iter in outer_iter:
    for inner_list in inner_iter:
        total = total + inner_list

我正在努力“翻译”代码。

最佳答案

如果数据嵌套两层深度,我们可以使用chain函数将迭代连接在一起,然后让sum(..) 计算可迭代的总和。所以:

<b>from itertools import chain</b>

sum(<b>chain.from_iterable(</b>outer_iter<b>)</b>)

chain.from_iterable 将可迭代的可迭代作为输入,并将其转换为一个可迭代,每次从可迭代中延迟获取元素。我们可以在上使用可迭代解包,但如果外部可迭代是一个无限列表,算法就会陷入困境(并最终耗尽内存)。

关于python - 使用 map-reduce/itertools 对嵌套迭代求和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47590595/

相关文章:

python - 用于顺序、条件和修改函数应用的高阶函数?

python - 在spark dataframe python中将二进制字符串的列转换为int

带有异步 def 的 python asyncio add_done_callback

javascript - 函数式编程和异步/ promise

scala - 重构一个小型 Scala 函数

python - 通过 Django Admin 将图像上传到 ImageField 时出错

python - 使用 django 和自定义脚本的 HTML 表单操作

python - 无论时态或形式如何匹配单词?

Python 脚本在 IDLE 中工作但不能作为 .desktop 图标

python - boolean 语句在应该为 false 时返回 true(使用 and & or)