Python list函数

Python list函数Python 内置函数 list 介绍 使用示例和注意事项

目录

描述

语法

使用示例

1. 创建一个空列表(无参调用list函数)

2. 将字符串转换为列表

3. 将元组转换为列表

4. 将字典转换为列表

5. 将集合转换为列表

6. 将其他可迭代序列转化为列表

注意事项

1. 参数必须是可迭代序列对象

将列表转换为列表


描述

list()函数是Python的内置函数。它可以将任何可迭代数据转换为列表类型,并返回转换后的列表。当参数为空时,list函数可以创建一个空列表。

语法

list(object)
名称 说明 备注
object 待转换为列表的数据类型 可省略的参数

使用示例

1. 创建一个空列表(无参调用list函数)

>>> test = list() >>> test []

2. 将字符串转换为列表

>>> test = list('cat') >>> test ['c', 'a', 't']

3. 将元组转换为列表

>>> a_tuple = ('I love Python.', 'I also love HTML.') >>> test = list(a_tuple) >>> test ['I love Python.', 'I also love HTML.']

4. 将字典转换为列表

>>> a_dict = {'China':'Beijing', 'Russia':'Moscow'} >>> test = list(a_dict) >>> test ['China', 'Russia']

⚠️注意:将字典转换为列表时,会将字典的值舍去,而仅仅将字典的键转换为列表。如果想将字典的值全部转换为列表,可以考虑使用字典方法dict.values()

5. 将集合转换为列表

>>> a_set = {1, 4, 'sdf'} >>> test = list(a_set) >>> test [1, 'sdf', 4]

6. 将其他可迭代序列转化为列表

下面的代码将range类型和map类型的可迭代序列转换为列表:

>>> test1 = list(range(10)) >>> test2 = list(map(int, [23.2, 33.1])) >>> test1 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> test2 [23, 33]

注意事项

1. 参数必须是可迭代序列对象

list函数的参数必须是可迭代对象。当选用不可迭代的对象作为参数时,Python报错。

>>> test = list(12) Traceback (most recent call last): File " 
   
     ", line 1, in 
    
      TypeError: 'int' object is not iterable 
     
   

将列表转换为列表

    可以使用list函数将列表转换为一个列表,这么做Python不会有任何的异常或者报错。它的作用是将参数列表进行深拷贝:

if __name__ == '__main__': source_list = ["a", "b", "c", "d"] new_list1 = list(source_list) print(id(source_list), id(new_list1)) # output:   new_list2 = source_list print(new_list1) # output: ['a', 'b', 'c', 'd'] print(new_list2) # output: ['a', 'b', 'c', 'd'] source_list[0] = "e" print(new_list1) # output: ['a', 'b', 'c', 'd'] print(new_list2) # output: ['e', 'b', 'c', 'd'] 

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/198888.html原文链接:https://javaforall.net

(0)
上一篇 2026年3月26日 下午2:17
下一篇 2026年3月26日 下午2:18


相关推荐

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号