问题描述
我需要逐步填充一个列表或一个列表元组.看起来像这样的东西:
I need to incrementally fill a list or a tuple of lists. Something that looks like this:
result = []
firstTime = True
for i in range(x):
for j in someListOfElements:
if firstTime:
result.append([f(j)])
else:
result[i].append(j)
为了让它不那么冗长更优雅,我想我会预先分配一个空列表的列表
In order to make it less verbose an more elegant, I thought I will preallocate a list of empty lists
result = createListOfEmptyLists(x)
for i in range(x):
for j in someListOfElements:
result[i].append(j)
预分配部分对我来说并不明显.当我执行 result = [[]] * x
时,我收到了一个对同一列表的 x
引用的列表,以便输出以下
The preallocation part isn't obvious to me. When I do result = [[]] * x
, I receive a list of x
references to the same list, so that the output of the following
result[0].append(10)
print result
是:
[[10], [10], [10], [10], [10], [10], [10], [10], [10], [10]]
我可以使用循环(result = [[] for i in range(x)]
),但我想知道是否存在无循环"解决方案.
I can use a loop (result = [[] for i in range(x)]
), but I wonder whether a "loopless" solution exists.
是获得我想要的东西的唯一途径
Is the only way to get what I'm looking for
推荐答案
result = [list(someListOfElements) for _ in xrange(x)]
这将生成 x 个不同的列表,每个列表都有一个 someListOfElements
列表的副本(该列表中的每个项目都是引用,但其所在的列表是一个副本).
This will make x distinct lists, each with a copy of someListOfElements
list (each item in that list is by reference, but the list its in is a copy).
如果更有意义,请考虑使用 copy.deepcopy(someListOfElements)
If it makes more sense, consider using copy.deepcopy(someListOfElements)
生成器和列表推导式和事物被认为非常pythonic.
Generators and list comprehensions and things are considered quite pythonic.
这篇关于如何在 Python 中创建空列表的列表或元组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!