Python list() 函数用法

2023-09-17 22:26:23

list() 方法从作为参数传递的包含所有元素的可迭代对象返回一个list对象。

语法:

list(iterable)

Parameter:

可迭代:(可选)要转换为列表的可迭代对象。

返回类型:

返回一个列表。

empty_list = list() # returns empty list
print("Empty list: ", empty_list)
print(type(empty_list))
num_list = list((1,2,3,4,5)) # converts tuple to list
print("tuple to list: ", num_list)
print(type(num_list))

输出:

Empty list:  []
<class 'list'>
tuple to list:  [1, 2, 3, 4, 5]
<class 'list'>

下面的示例使用 list() 方法将其他类型的可迭代stringsetDictionary转换为列表

print("string to list: ", list('Hello World')) # converts string to list
print("set to list: ", list({1,2,3,4,5})) # converts set to list
print("dictionary to list: ", list({1:'one',2:'two',3:'three'})) # converts dict keys to list

输出:

string to list:  ['H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd']
set to list:  [1, 2, 3, 4, 5]
dictionary to list:  [1, 2, 3]

如果传递其他类型的值而不是可迭代的值,则list()方法会引发错误。

lst= list(123456)

输出:

Traceback (most recent call last):
    list(123456)
TypeError: 'int' object is not iterable