Python: How to initialize a nested list with empty values which i can append to(如何使用空值初始化嵌套列表,我可以将其追加到该列表中)
本文介绍了如何使用空值初始化嵌套列表,我可以将其追加到该列表中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在学习蟒蛇,结果撞到了墙上。 我正在尝试定义一个2D列表,稍后我可以使用它来附加值。这与宽*高的网格相对应
我尝试使用[]来初始化空列表,但随后忽略了wid。 我尝试使用None作为占位符,但无法追加
wid = 3
hgt = 3
l1 = [[]*wid ] * hgt
l = [[None]*wid ] * hgt
l[1][1].append("something")
结果
l1: [[], [], []]
l: [[None, None, None], [None, None, None], [None, None, None]]
错误:
append: AttributeError: 'NoneType' object has no attribute 'append'
预期结果:[[[], [], []], [[], [], []], [[], [], []]]
推荐答案
尝试在列表理解中使用列表理解:
>>> [ [ [] for i in range(wid) ] for i in range(hgt) ]
[[[], [], []], [[], [], []], [[], [], []]]
注意:这比列表乘法更可取,因为这些列表中的每个列表都是唯一的。比较:
>>> x = [ [[] for i in range(wid)] for i in range(hgt) ]
>>> x[1][1].append('a')
>>> x
[[[], [], []], [[], ['a'], []], [[], [], []]]
与
>>> y = [ [[]] * wid for i in range(hgt) ]
>>> y[1][1].append('a')
>>> y
[[[], [], []], [['a'], ['a'], ['a']], [[], [], []]]
与
>>> z = [ [[]] * wid ] * hgt
>>> z[1][1].append('a')
>>> z
[[['a'], ['a'], ['a']], [['a'], ['a'], ['a']], [['a'], ['a'], ['a']]]
其中,在第二和第三种情况下,‘a’出现在多个单元格中!使用None
并不能避免此问题:
>>> m = [ [None] * wid ] * hgt
>>> m
[[None, None, None], [None, None, None], [None, None, None]]
>>> if m[1][1] is None:
... m[1][1] = ['a']
... else:
... m[1][1].append('a')
...
>>> m
[[None, ['a'], None], [None, ['a'], None], [None, ['a'], None]]
tl;dr-使用双重列表理解。在我看来,无论如何,这是最具可读性的选项。
这篇关于如何使用空值初始化嵌套列表,我可以将其追加到该列表中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
沃梦达教程
本文标题为:如何使用空值初始化嵌套列表,我可以将其追加到该列表中


基础教程推荐
猜你喜欢
- Python 的 List 是如何实现的? 2022-01-01
- 使用Python匹配Stata加权xtil命令的确定方法? 2022-01-01
- 将 YAML 文件转换为 python dict 2022-01-01
- 哪些 Python 包提供独立的事件系统? 2022-01-01
- 如何在Python中绘制多元函数? 2022-01-01
- 合并具有多索引的两个数据帧 2022-01-01
- 使用 Google App Engine (Python) 将文件上传到 Google Cloud Storage 2022-01-01
- 如何在 Python 中检测文件是否为二进制(非文本)文 2022-01-01
- 使 Python 脚本在 Windows 上运行而不指定“.py";延期 2022-01-01
- 症状类型错误:无法确定关系的真值 2022-01-01