list()函数在Python中做什么? [英] What does the list() function do in Python?

查看:186
本文介绍了list()函数在Python中做什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I know that the list() constructor creates a new list but what exactly are its characteristics?

  1. 呼叫list((1,2,3,4,[5,6,7,8],9))会发生什么?

呼叫list([[[2,3,4]]])会发生什么?

呼叫list([[1,2,3],[4,5,6]])会发生什么?

据我所知,调用构造函数list会删除最外面的括号(元组或列表),并将其替换为[].这是真的? list()还有什么其他细微差别?

From what I can tell, calling the constructor list removes the most outer braces (tuple or list) and replaces them with []. Is this true? What other nuances does list() have?

推荐答案

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

list() converts the the iterable passed to it to a list. If the itertable is already a list then a shallow copy is returned, i.e only the outermost container is new rest of the objects are still the same.

>>> 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

这篇关于list()函数在Python中做什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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