Python 使用列表理解或映射()从现有列表创建更大的列表
我试图生成一个列表来索引坐标(x,y和z),给定一组原子索引。我的问题很简单,就是如何优雅地离开这个列表:Python 使用列表理解或映射()从现有列表创建更大的列表,python,list,list-comprehension,Python,List,List Comprehension,我试图生成一个列表来索引坐标(x,y和z),给定一组原子索引。我的问题很简单,就是如何优雅地离开这个列表: atom_indices = [0, 4, 5, 8] coord_indices = [0, 1, 2, 12, 13, 14, 15, 16, 17, 24, 25, 26] 在此列表中: atom_indices = [0, 4, 5, 8] coord_indices = [0, 1, 2, 12, 13, 14, 15, 16, 17, 24, 25, 26] 到目前为止
atom_indices = [0, 4, 5, 8]
coord_indices = [0, 1, 2, 12, 13, 14, 15, 16, 17, 24, 25, 26]
在此列表中:
atom_indices = [0, 4, 5, 8]
coord_indices = [0, 1, 2, 12, 13, 14, 15, 16, 17, 24, 25, 26]
到目前为止,我想到的最简单的阅读/理解方法是:
coord_indices = []
for atom in atom_indices:
coord_indices += [3 * atom,
3 * atom + 1,
3 * atom + 2]
但这看起来不太像蟒蛇。如果没有列表或元组列表,有没有更好的方法我没有想到?怎么样:
>>> 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]
我们可以按照编写循环的相同顺序在列表理解中嵌套循环,也就是说,这基本上是
coords = []
for a in atom_indices:
for k in range(3):
coords.append(3*a+k)
不过,如果循环在这种情况下更清晰,就不要害怕。出于我从未完全理解的原因,有些人觉得他们在水平编写代码而不是垂直编写代码时更聪明,尽管这会使调试变得更困难。怎么样:
>>> 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]
我们可以按照编写循环的相同顺序在列表理解中嵌套循环,也就是说,这基本上是
coords = []
for a in atom_indices:
for k in range(3):
coords.append(3*a+k)
不过,如果循环在这种情况下更清晰,就不要害怕。出于我从未完全理解的原因,有些人觉得他们水平编写代码比垂直编写代码更聪明,尽管这会使调试变得更困难。我相信列表理解可以更快,因为它们被下推到c代码@DSM感谢您的回答,您的评论是有效的。然而,我认为在这种情况下,人们会非常清楚地知道3*a+k部分发生了什么。@imaging:不过好处通常很小。如果您实际所做的是昂贵的,那么它将主导循环成本,或者您应该使用其他类似numpy
的东西。如果一开始不贵,那就不值得担心了。[顺便说一句,我认为你有错误的链接。]我相信列表理解可以更快,因为它们被下推到c代码@DSM感谢您的回答,您的评论是有效的。然而,我认为在这种情况下,人们会非常清楚地知道3*a+k部分发生了什么。@imaging:不过好处通常很小。如果您实际所做的是昂贵的,那么它将主导循环成本,或者您应该使用其他类似numpy
的东西。如果一开始不贵,那就不值得担心了。[顺便说一句,我想你的链接错了。]