创建一个空字典列表 [英] Create a list of empty dictionaries

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

问题描述

我想创建一个包含空目录的可变长度列表。

  n = 10#列表大小
foo = []
for _ in range(n)
foo.append({})

你会这样做吗,还是有什么样的?

  a = [{} * n] 


解决方案

列出对救援的理解! >

  foo = [{range for _ in range(n)] 

没有更短的符号,恐怕。在Python 2中,您使用 xrange(n)而不是 range(n)以避免实现无用的列表。 p>

替代方案 [{}] * n 创建一个长度 n 只有一个字典,引用 n 次。这将导致令人讨厌的惊喜,当添加键到字典。


I want to create a list of variable length containing empty directories.

n = 10 # size of list
foo = []
for _ in range(n)
    foo.append({})

Would you do this the same way, or is there something like?

a = [{}*n]

解决方案

List comprehensions to the rescue!

foo = [{} for _ in range(n)]

There is no shorter notation, I am afraid. In Python 2 you use xrange(n) instead of range(n) to avoid materializing a useless list.

The alternative, [{}] * n creates a list of length n with only one dictionary, referenced n times. This leads to nasty surprises when adding keys to the dictionary.

这篇关于创建一个空字典列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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