使用列表推导或map()从现有列表创建更大的列表

Kyl*_*S-C 0 python list-comprehension list

我正在尝试生成一个列表来索引坐标(x,y和z),给定一组原子索引.我的问题很简单,如何优雅地从这个列表:

atom_indices = [0, 4, 5, 8]
Run Code Online (Sandbox Code Playgroud)

到此列表:

coord_indices = [0, 1, 2, 12, 13, 14, 15, 16, 17, 24, 25, 26]
Run Code Online (Sandbox Code Playgroud)

到目前为止,我最简单的阅读/理解方式是:

coord_indices = []
for atom in atom_indices:
    coord_indices += [3 * atom,
                      3 * atom + 1,
                      3 * atom + 2]
Run Code Online (Sandbox Code Playgroud)

但这似乎不是Pythonic.如果没有列表列表或元组列表,有没有更好的方法?

DSM*_*DSM 5

怎么样:

>>> atom_indices = [0, 4, 5, 8]
>>> coords = [3*a+k for a in atom_indices for k in range(3)]
>>> coords
[0, 1, 2, 12, 13, 14, 15, 16, 17, 24, 25, 26]
Run Code Online (Sandbox Code Playgroud)

我们可以按照我们编写循环的相同顺序在列表推导中嵌套循环,这基本上就是这样

coords = []
for a in atom_indices: 
    for k in range(3): 
        coords.append(3*a+k)
Run Code Online (Sandbox Code Playgroud)

for但是,如果他们在这种情况下更清楚,不要害怕循环.由于我从未完全理解的原因,有些人觉得他们在水平而不是垂直编写代码时更聪明,即使它使调试更难.