简体   繁体   English

嵌套列表理解 - python

[英]Nested list comprehension - python

Probably there is quite an easy solution for this, but I just can't seem to find it.可能有一个非常简单的解决方案,但我似乎无法找到它。

I have multiple names which I'm trying to join together:我有多个名称,我试图将它们连接在一起:

dir_name = ['bseg', 'ekpo']
sys_name = ['a3p065', 'a3p100']
paths = [os.path.join(a, b) for a in (os.path.join(os.getcwd(), name) for name in sys_name) for b in dir_name]

paths gives me: paths给了我:

['C:path\\a3p065\\bseg', 'C:path\\a3p065\\ekpo', 'C:path\\a3p100\\bseg', 'C:path\\a3p100\\ekpo']

However I need such a format:但是我需要这样的格式:

[['C:path\\a3p065\\bseg', 'C:path\\a3p065\\ekpo'], ['C:path\\a3p100\\bseg', 'C:path\\a3p100\\ekpo']]

A nesting of lists requires nested list comprehensions.列表的嵌套需要嵌套的列表推导。 One to iterate over the dir_names , and another for the sys_names .一个迭代dir_names ,另一个迭代sys_names Try this:尝试这个:

dir_name = ['bseg', 'ekpo']
sys_name = ['a3p065', 'a3p100']
paths = [[os.path.join(a, b) for a in (os.path.join(os.getcwd(), name) for name in sys_name)] for b in dir_name]

You don't actually have a nested list comprehension;您实际上没有嵌套列表理解; you have a single comprehension with two iterators.你有两个迭代器的单一理解。

Compare相比

[x for y in z for x in y]  # One comprehension, two iterators

with

[[x for x in y] for y in z]  # Two comprehensions, each with a single iterator

For your case, you want something modeled on the latter:对于您的情况,您需要以后者为模型的东西:

dir_name = ['bseg', 'ekpo']
sys_name = ['a3p065', 'a3p100']


paths = [[os.path.join(os.getcwd(), s, d) for d in dir_name] for s in sys_name]

Something like this?像这样的东西? (I'm using "." for the root path, but feel free to use os.getcwd() .) (我使用"."作为根路径,但请随意使用os.getcwd() 。)

import os

dir_names = ["bseg", "ekpo"]
sys_names = ["a3p065", "a3p100"]
localized_sys_names = [os.path.join(".", name) for name in sys_names]
paths = [
    [os.path.join(sys_name, dir_name) for sys_name in sys_names]
    for dir_name in dir_names
]

print(paths)

Output: Output:

[['a3p065/bseg', 'a3p100/bseg'], ['a3p065/ekpo', 'a3p100/ekpo']]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM