python - python列表和字典可以无限嵌套吗?

标签 python

最近发现python的list和dictionary可以这样多层嵌套

a = {'a1':[{'a2':{'a3':[4,5,6]}}]}

所以想问下嵌套层级有技术限制吗? 如果没有,嵌套级别是否有常规限制,它是什么?

最佳答案

唯一的限制是内存。给定无限内存,您可以无限嵌套 Python 对象。

演示:

>>> root = lst = []
>>> levels = 0
>>> while True:
...     lst.append([])
...     lst = lst[-1]
...     levels += 1
...     if levels % 1000000 == 0:  # every 1 million
...         print levels
... 
1000000
2000000
3000000
4000000
5000000
6000000
7000000
8000000
9000000
10000000
11000000
# ....
# [ slower and slower as the system starts to swap ]
# ....
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
MemoryError

不过,为了我的理智,我在 3000 万个对象处将其杀死。

关于python - python列表和字典可以无限嵌套吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22224094/

相关文章:

python - 为什么使用 Pandas.to_datetime 进行的这种日期转换比某些替代方法慢得多?

python - 运行 X 次进程的更多 Pythonic 方式

python - 用中位数替换 NaN 值?

python - 使用 Django Channels 将信息发送到所有连接的客户端

python - 自 apache arrow 1.0.1 发布以来用于长期存储的 Feather 格式

python - 在 macOS/OSX 上配置 flake8

python - 如何用零填充字符串?

python - 如何在特定时间执行程序

python - 在 Python 中解析未格式化的日期

python - 重新缩放给定最大值和最小值之间的值,其中最大值为正,最小值为负