You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用一行列表推导式将executor.map返回的列表生成器合并为单列表

正确实现代码

你要的一行列表推导式写法如下,完全等价于你给出的双层循环逻辑:

with futures.ThreadPoolExecutor(max_workers=20) as executor:
    dirs = [w for workers in executor.map(partial_subdirs, prefix_list) for w in workers]

说明

  • 列表推导式的多层循环顺序和常规for循环书写顺序完全一致:先迭代executor.map返回的每一个子结果workers,再迭代workers中的每一个元素w,最终直接收集所有w生成一维列表,不会出现嵌套结构。
  • 你之前的写法仅迭代了第一层的executor.map结果,将每个子列表直接作为外层列表的元素,所以才会得到嵌套结构,额外的f + f运算也不符合你要提取子元素的需求。

可选替代方案

你也可以借助itertools.chain实现列表打平,写法更简洁:

from itertools import chain

with futures.ThreadPoolExecutor(max_workers=20) as executor:
    dirs = list(chain.from_iterable(executor.map(partial_subdirs, prefix_list)))

内容的提问来源于stack exchange,提问作者anthony12345

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 16:09:01