Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
484 views
in Technique[技术] by (71.8m points)

memory management - How to create a list or tuple of empty lists in 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)

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

is:

[[10], [10], [10], [10], [10], [10], [10], [10], [10], [10]]

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
result = [list(someListOfElements) for _ in xrange(x)]

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).

If it makes more sense, consider using copy.deepcopy(someListOfElements)

Generators and list comprehensions and things are considered quite pythonic.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...