开发者

How to generate a list of 150 cases initialised with a dict in Python?

I would like to create a list like开发者_开发百科 this

list = []

for i in range(150):
    list.append({'open': False, 'serve': False})

But is there a better way in Python to do it ?


With a list comprehension (don't use list as a variable name, as it shadows the python built-in):

# use range() in Python 3
l = [{'open': False, 'serve': False} for i in xrange(150)]


Whatever you do, don't try list = [{'open':False,'serve':False}]*150, as you will have the same dictionary 150 times. :D

You will then get fun behavior, like

>>> list[0]['open'] = True
>>> list[1]['open'] = False
>>> print list[0]['open']
False

>>> list[0] is list[1]
True

As gs noted, tn python 2.6, you can use namedtuple, which is easier on memory:

from collections import namedtuple
Socket = namedtuple('Socket', 'open serve')
sockets = [Socket(False,False) for i in range(150)]


The list comprehension to build your data structure is probably slightly more efficient. It's also much much terser. Sometimes the terseness is a nice thing, and sometimes it just obscures what is going on. In this case I think the listcomp is pretty clear.

But the listcomp and the for loop both end up building exactly the same thing for you, so this is really a case where there is no "best" answer.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜