Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

list函数python用法

作者:风外听竹   发布日期:2026-03-27   浏览:86

# 示例代码:list函数的用法

# 1. 使用list()函数将其他可迭代对象转换为列表
# 将字符串转换为列表
string = "hello"
list_from_string = list(string)
print(list_from_string)  # 输出: ['h', 'e', 'l', 'l', 'o']

# 将元组转换为列表
tuple_data = (1, 2, 3, 4, 5)
list_from_tuple = list(tuple_data)
print(list_from_tuple)  # 输出: [1, 2, 3, 4, 5]

# 将集合转换为列表
set_data = {10, 20, 30}
list_from_set = list(set_data)
print(list_from_set)  # 输出: [10, 20, 30] (注意:集合是无序的,所以输出顺序可能不同)

# 将字典的键或值转换为列表
dict_data = {'a': 1, 'b': 2, 'c': 3}
list_from_dict_keys = list(dict_data.keys())
list_from_dict_values = list(dict_data.values())
print(list_from_dict_keys)  # 输出: ['a', 'b', 'c']
print(list_from_dict_values)  # 输出: [1, 2, 3]

# 2. 使用list()函数创建空列表
empty_list = list()
print(empty_list)  # 输出: []

# 3. 使用list()函数直接传递可迭代对象
range_data = range(1, 6)
list_from_range = list(range_data)
print(list_from_range)  # 输出: [1, 2, 3, 4, 5]

解释说明:

  • list() 函数可以将其他可迭代对象(如字符串、元组、集合、字典等)转换为列表。
  • 如果不传递参数,list() 会创建一个空列表。
  • 对于字典,list() 只会提取键作为列表元素,如果需要提取值,可以使用 dict.values() 方法。

上一篇:python的flask框架干啥的

下一篇:python return函数用法

大家都在看

python 二维码识别

python excel 库

python时间格式

pythoneval函数用法

列表切片操作python

python读取文件路径

staticmethod在python中有

python 保存json文件

python开发windows应用程序

python中len是什么意思

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站