使用列表推导创建嵌套列表

时间:2014-11-12 23:40:21

标签: python list list-comprehension

我有以下列表:

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 l1_index in l1 for l2_value in l2[l1_index]]

但失去了原来的筑巢。

这是我想要的:

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

2 个答案:

答案 0 :(得分:2)

使用nested list comprehension代替包含两个for ... in ...子句的单个

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

如果你要传播它,它看起来像:

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

演示:

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

答案 1 :(得分:0)

在这种情况下,我个人避免使用嵌套列表推导。它并不是特别清楚发生了什么。

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)