Python list()函数

描述

Python的list函数可以将其他数据类型转换为列表类型,并返回转换后的列表。当参数为空时,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']

⚠️注意:将字典转换为列表时,会将字典的值舍去,而仅仅将字典的键转换为列表。如果想将字典的值全部转换为列表,可以考虑使用字典函数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 "<stdin>", line 1, in <module>
TypeError: 'int' object is not iterable

2. 无意义的转换----将列表转换为列表

    可以使用list函数将列表转换为一个列表,虽然这么做Python不会有任何的异常或者报错----但是这种行为显然是没有意义且浪费资源的行为。

>>> a_list = ['Python', 'C', 'Java', 'HTML', 'CSS']
>>> test = list(a_list)
>>> test
['Python', 'C', 'Java', 'HTML', 'CSS']

猜你喜欢

转载自blog.csdn.net/TCatTime/article/details/82947385