python - list() 函数在 Python 中有什么作用?

标签 python list python-3.x

我知道 list() 构造函数会创建一个新列表,但它的特性究竟是什么?

  1. 当您调用 list((1,2,3,4,[5,6,7,8],9)) 时会发生什么?

  2. 当您调用 list([[[2,3,4]]]) 时会发生什么?

  3. 当您调用 list([[1,2,3],[4,5,6]]) 时会发生什么?

据我所知,调用构造函数 list 会删除最外层的大括号(元组或列表)并将它们替换为 []。这是真的? list() 还有哪些细微差别?

最佳答案

list() 将传递给它的可迭代对象转换为列表。如果 itertable 已经是一个列表,则返回一个浅拷贝,即只有最外层的容器是新的,其余的对象仍然相同。

>>> t = (1,2,3,4,[5,6,7,8],9)
>>> lst = list(t) 
>>> lst[4] is t[4]  #outermost container is now a list() but inner items are still same.
True

>>> lst1 = [[[2,3,4]]]
>>> id(lst1)
140270501696936
>>> lst2 = list(lst1)
>>> id(lst2)
140270478302096
>>> lst1[0] is lst2[0]
True

关于python - list() 函数在 Python 中有什么作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26581397/

相关文章:

python - Tkinter 在框架中加载图像

python - 从 2.3.1 升级到 Spark2.4.2 但 mongodb 连接器停止工作

python - virtualenvwrapper 和 Python 3

python - 根据相应的 numpy 数组值分割 Dataframe

java - 防止并发修改异常的最佳方法

list - 使用 Red 语言从多个列表中获取值到一个列表

c# - 如何在不反序列化旧数据的情况下将新项目附加到序列化的 xml 数据中?

python - 导入错误: cannot import name 'ft2font' from partially initialized module 'matplotlib'

Python 语法错误 : Non-UTF-8

python - 为 Django/Python 3 配置 Azure