如何在Python中创建一个空列表或空列表元组? [英] How to create a list or tuple of empty lists in Python?

查看:235
本文介绍了如何在Python中创建一个空列表或空列表元组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要以增量方式填充一个列表或列表的元组.看起来像这样:

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中创建一个空列表或空列表元组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆