【问题标题】:Map three lists映射三个列表
【发布时间】:2023-01-24 19:48:11
【问题描述】:

我有以下三个列表:

paths = ["c:/path/path", "d:/path/path"]
folder_one = ["fol1", "fol2"]
folder_two = ["folder1", "folder2"]

我如何映射这三个列表,使 output 看起来像这样:

("c:/path/path", "fol1")
("c:/path/path", "fol2")
("d:/path/path", "folder1")
("d:/path/path", "folder2")

到目前为止我有:

somelists = [paths] + [folder_one + folder_two]
for element in itertools.product(*somelists):
    print(element)

但它也会生成像这样的元组:("c:/path/path", "folder1")

谁能给我一个提示?

【问题讨论】:

  • 迭代 zip(paths, (folder_one, folder_two)) 应该给你一个起点。
  • 预期结果是什么?将第一个列表映射到第一个元素等等?或者是其他东西?
  • 使用 zip 可能是执行此操作的最佳和最 pythonic 方式。为 zip(paths, folder_one, folder_two) 的每个输入创建一个元组

标签: python


【解决方案1】:

这应该给你想要的:

[f"{p}/{f}" for p, file in zip(paths, (folder_one, folder_two)) for f in file]
>>> ['c:/path/path/fol1',
 'c:/path/path/fol2',
 'd:/path/path/folder1',
 'd:/path/path/folder2']

您可以将其拆分为以下部分:

zip(paths, (folder_one, folder_two))

将每个路径连接到文件夹列表(folder_one、folder_two)。

然后遍历每个路径和列表中的文件:

for p, file in zip(paths, (folder_one, folder_two))

file 是一个包含文件的列表。

最后一部分是遍历文件列表中的每个文件:

for f in file

编辑

抱歉,我教过您想要路径,并针对所需的输出进行了更改:

[(p,f) for p, file in zip(paths, (folder_one, folder_two)) for f in file]
>>> [('c:/path/path', 'fol1'),
 ('c:/path/path', 'fol2'),
 ('d:/path/path', 'folder1'),
 ('d:/path/path', 'folder2')]

【讨论】:

  • 您可以添加代码的输出,以便我们可以将其与 OP 指定的输出进行比较吗?
  • 是的,我已经添加了输出
  • @3dSpatialUser 谢谢
【解决方案2】:

对于您的特定输出格式,您可以使用以下内容:

import itertools
paths = ["c:/path/path", "d:/path/path"]
per_path_folders = [["fol1", "fol2"], ["folder1", "folder2"]]
all_paths = []
for path, folders in zip(paths, per_path_folders):
  all_paths.extend(itertools.product([path], folders))

print(all_paths)

输出:

[('c:/path/path', 'fol1'), ('c:/path/path', 'fol2'), ('d:/path/path', 'folder1'), ('d: /路径/路径', 'folder2')]

【讨论】:

    【解决方案3】:

    您可以使用zip_longest (here)

    list(itertools.zip_longest(paths, folder_one+folder_two))
    

    输出 -

    [('c:/path/path', 'fol1'), ('d:/path/path', 'fol2'), (None, 'folder1'), (None, 'folder2')]

    【讨论】:

    • 这看起来不像指定的输出。
    猜你喜欢
    • 1970-01-01
    • 2013-11-25
    • 1970-01-01
    • 1970-01-01
    • 2014-03-28
    • 1970-01-01
    • 2012-07-17
    • 1970-01-01
    • 2011-12-04
    相关资源
    最近更新 更多