Home > Blockchain >  Nested list comprehension - python
Nested list comprehension - python

Time:11-24

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:

['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']]

CodePudding user response:

A nesting of lists requires nested list comprehensions. One to iterate over the dir_names, and another for the 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]

CodePudding user response:

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]

CodePudding user response:

Something like this? (I'm using "." for the root path, but feel free to use 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:

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