在Python中预分配或不预分配列表 [英] To preallocate or not to preallocate lists in Python
问题描述
何时和不应该在python中预分配列表列表? 例如,我有一个接受2个列表并从中创建列表列表的函数. 很像,但不完全是矩阵乘法.我应该预分配结果吗?
When should and shouldn't I preallocate a list of lists in python? For example, I have a function that takes 2 lists and creates a lists of lists out of it. Quite like, but not exactly, matrix multiplication. Should I preallocate the result,
X = Len(M)
Y = Len(F)
B = [[None for y in range(Y)] for x in range(X)]
for x in range(X):
for y in range(Y):
B[x][y] = foo(M[x], F[y])
return B
还是在创建过程中动态创建它?
or dynamically create it as I go?
B = []
for m in M:
B.append([])
for f in F:
B[-1].append(foo(m, f))
return B
预分配似乎是不必要的,并且可能会更慢,但动态地看起来很模糊.特别是B[-1].append(...)
似乎难以辨认.
Preallocating seems unnecessary and perhaps slower, but dynamically looks obfuscated. In particular, B[-1].append(...)
seems illegible.
推荐答案
使用列表理解来简单地创建列表:
Simply create the list using list comprehension:
[[foo(m, f) for f in F] for m in M]
与预分配有关:预分配None
的列表
Related to pre-allocation: Pre-allocating a list of None
这篇关于在Python中预分配或不预分配列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!