温馨提示×

python中list函数的用法是什么

小亿
97
2023-11-09 09:10:33
栏目: 编程语言

在Python中,list()函数用于将其他可迭代对象(如字符串、元组、字典等)转换为列表。其语法如下:

list(iterable)

参数:
- iterable(可迭代对象):要转换为列表的可迭代对象。
返回值:返回一个新的列表。
示例:

string = "Hello"
list_string = list(string)
print(list_string)  # 输出:['H', 'e', 'l', 'l', 'o']
tuple1 = (1, 2, 3)
list_tuple = list(tuple1)
print(list_tuple)  # 输出:[1, 2, 3]
dict1 = {'a': 1, 'b': 2, 'c': 3}
list_dict = list(dict1)
print(list_dict)  # 输出:['a', 'b', 'c']

注意:在使用list()函数转换字典时,只会返回字典的键(而不是值)。如果需要转换为包含键值对的列表,可以使用dict.items()方法。

0