0

I have the following lists:

path='/my/path/'
l1=[2,0,1]
l2=[['a.txt','b.txt','c.txt'],['d.txt','f.txt','g.txt'],['h.txt','i.txt','j.txt']]

and I wrote a list comprehension to add the full path:

[os.path.join(path, 'list%d'%l1_index, l2_value) for l1_index in l1 for l2_value in l2[l1_index]]

but lost the original nesting.

Here's what I'd like to get:

[ ['/my/path/list2/h.txt','/my/path/list2/i.txt','/my/path/list2/j.txt'], ['/my/path/list0/a.txt','/my/path/list0/b.txt','/my/path/list0/c.txt'], ['/my/path/list1/d.txt','/my/path/list1/f.txt','/my/path/list1/g.txt'] ]
1
  • Is there a good reason for using a list comprehension here? It's one of those cases where you end up obscuring the intent of the code. Commented Nov 12, 2014 at 23:45

2 Answers 2

2

Use a nested list comprehension instead of a single one with two for ... in ... clauses:

[[os.path.join(path, 'list%d'%l1_index, l2_value) for l2_value in l2[l1_index]] for l1_index in l1]

If you were to spread this out, it would look like:

[
    [
        os.path.join(path, 'list%d'%l1_index, l2_value)
        for l2_value in l2[l1_index]
    ]
    for l1_index in l1
]

Demo:

>>> import os
>>> path='/my/path/'
>>> l1=[2,0,1]
>>> l2=[['a.txt','b.txt','c.txt'],['d.txt','f.txt','g.txt'],['h.txt','i.txt','j.txt']]
>>> [[os.path.join(path, 'list%d'%l1_index, l2_value) for l2_value in l2[l1_index]] for l1_index in l1]
[['/my/path/list2\\h.txt', '/my/path/list2\\i.txt', '/my/path/list2\\j.txt'], ['/my/path/list0\\a.txt', '/my/path/list0\\b.txt', '/my/path/list0\\c.txt'], ['/my/path/list1\\d.txt', '/my/path/list1\\f.txt', '/my/path/list1\\g.txt']]
>>>
Sign up to request clarification or add additional context in comments.

Comments

0

Personally I'd avoid the nested list comprehensions in this case. It's not especially clear what's going on.

import os

path = '/my/path'
l1 = [2,0,1]
l2 = [
  ['a.txt','b.txt','c.txt'],
  ['d.txt','f.txt','g.txt'],
  ['h.txt','i.txt','j.txt']
]

pathset = []
for l in l1:
    to_add = l2[l]
    paths = [os.path.join(path, 'list%s' % l, filename) for filename in to_add]
    pathset.append(paths)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.