python常用得内置函数解析——list()函数
ython 中最常用的内置函数之一 list()。
1. 函数定义
list() 函数用于创建一个新的列表对象。
- 语法:list([iterable])
- 参数:
- iterable:可选,任何可迭代对象(字符串、元组、集合、字典、生成器等)
- 返回值:一个新的列表对象
2. 基本用法示例
创建空列表
# 创建空列表
empty_list = list()
print(empty_list) # 输出: []
print(type(empty_list)) # 输出: <class 'list'>
# 等价于
empty_list2 = []
print(empty_list2) # 输出: []
从各种可迭代对象创建列表
# 从字符串创建(字符列表)
char_list = list("hello")
print(char_list) # 输出: ['h', 'e', 'l', 'l', 'o']
# 从元组创建
tuple_data = (1, 2, 3, 4)
list_from_tuple = list(tuple_data)
print(list_from_tuple) # 输出: [1, 2, 3, 4]
# 从集合创建(顺序可能不同)
set_data = {1, 2, 3, 4}
list_from_set = list(set_data)
print(list_from_set) # 输出: [1, 2, 3, 4](顺序可能变化)
# 从范围对象创建
range_obj = range(5)
list_from_range = list(range_obj)
print(list_from_range) # 输出: [0, 1, 2, 3, 4]
从字典创建
# 从字典创建(默认获取键)
dict_data = {'a': 1, 'b': 2, 'c': 3}
keys_list = list(dict_data)
print(keys_list) # 输出: ['a', 'b', 'c']
# 获取键列表
keys_list = list(dict_data.keys())
print(keys_list) # 输出: ['a', 'b', 'c']
# 获取值列表
values_list = list(dict_data.values())
print(values_list) # 输出: [1, 2, 3]
# 获取键值对列表
items_list = list(dict_data.items())
print(items_list) # 输出: [('a', 1), ('b', 2), ('c', 3)]
3. 与列表字面量[]的比较
|
特性 |
list() |
[] |
|
语法 |
函数调用 |
字面量 |
|
可读性 |
更明确 |
更简洁 |
|
性能 |
稍慢 |
稍快 |
|
动态创建 |
适合 |
不适合 |
|
空列表 |
list() |
[] |
import timeit
# 性能比较
time_list_func = timeit.timeit('list()', number=1000000)
time_list_literal = timeit.timeit('[]', number=1000000)
print(f"list() 时间: {time_list_func:.6f}秒")
print(f"[] 时间: {time_list_literal:.6f}秒")
# [] 一般比 list() 稍快
4. 实际应用场景
场景1:数据转换和处理
# 字符串处理
text = "apple,banana,cherry"
fruits = list(text.split(','))
print(fruits) # 输出: ['apple', 'banana', 'cherry']
# 数字处理
numbers_str = "12345"
digits = list(map(int, numbers_str))
print(digits) # 输出: [1, 2, 3, 4, 5]
# 矩阵转置
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
transposed = list(map(list, zip(*matrix)))
print(transposed) # 输出: [[1, 4, 7], [2, 5, 8], [3, 6, 9]]
场景2:生成器表达式转换为列表
# 生成器表达式
squares_gen = (x**2 for x in range(10))
print(squares_gen) # 输出: <generator object <genexpr> at 0x...>
# 转换为列表
squares_list = list(squares_gen)
print(squares_list) # 输出: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
# 过滤数据
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_numbers = list(x for x in numbers if x % 2 == 0)
print(even_numbers) # 输出: [2, 4, 6, 8, 10]
场景3:数据清洗和规范化
def clean_data(data):
"""清洗数据,确保返回列表"""
if data is None:
return list()
if isinstance(data, (str, bytes)):
# 如果是字符串,按空格分割
return list(data.split())
try:
# 尝试转换为列表
return list(data)
except TypeError:
# 如果不能转换,包装成列表
return [data]
# 测试数据清洗
print(clean_data("hello world")) # 输出: ['hello', 'world']
print(clean_data((1, 2, 3))) # 输出: [1, 2, 3]
print(clean_data(123)) # 输出: [123]
print(clean_data(None)) # 输出: []
场景4:分批处理数据
def batch_process(data, batch_size=3):
"""将数据分批处理"""
batches = []
for i in range(0, len(data), batch_size):
batch = list(data[i:i + batch_size])
batches.append(batch)
return batches
# 测试分批处理
data = [1, 2, 3, 4, 5, 6, 7, 8, 9]
batches = batch_process(data, 4)
print(batches) # 输出: [[1, 2, 3, 4], [5, 6, 7, 8], [9]]
5. 高级用法和技巧
多维列表创建
# 创建二维列表(矩阵)
matrix = list(list(range(3)) for _ in range(3))
print(matrix) # 输出: [[0, 1, 2], [0, 1, 2], [0, 1, 2]]
# 使用列表推导式创建嵌套列表
nested = list([i, i*2] for i in range(5))
print(nested) # 输出: [[0, 0], [1, 2], [2, 4], [3, 6], [4, 8]]
与map()和filter()配合使用
# map() + list()
numbers = [1, 2, 3, 4, 5]
squared = list(map(lambda x: x**2, numbers))
print(squared) # 输出: [1, 4, 9, 16, 25]
# filter() + list()
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
print(even_numbers) # 输出: [2, 4]
# 组合使用
result = list(map(str, filter(lambda x: x > 2, numbers)))
print(result) # 输出: ['3', '4', '5']
深度拷贝列表
import copy
original = [[1, 2], [3, 4]]
# 浅拷贝
shallow_copy = list(original)
# 深拷贝
deep_copy = list(copy.deepcopy(original))
# 修改原列表会影响浅拷贝,但不影响深拷贝
original[0][0] = 99
print("原列表:", original) # 输出: [[99, 2], [3, 4]]
print("浅拷贝:", shallow_copy) # 输出: [[99, 2], [3, 4]]
print("深拷贝:", deep_copy) # 输出: [[1, 2], [3, 4]]
6. 错误处理和边界情况
# 不可迭代对象
try:
result = list(123) # 整数不可迭代
except TypeError as e:
print(f"错误: {e}") # 输出: 'int' object is not iterable
# None 处理
try:
result = list(None) # None 不可迭代
except TypeError as e:
print(f"错误: {e}") # 输出: 'NoneType' object is not iterable
# 空可迭代对象
empty_iter = iter([])
result = list(empty_iter)
print(result) # 输出: []
# 无限生成器(小心使用!)
def infinite_gen():
i = 0
while True:
yield i
i += 1
# 不要这样做:会无限循环
# infinite_list = list(infinite_gen())
7. 性能优化技巧
# 预分配列表大小(对于大型列表)
size = 1000
# 不推荐:不断追加
result = []
for i in range(size):
result.append(i)
# 推荐:预分配或使用列表推导式
result = [0] * size # 预分配
for i in range(size):
result[i] = i
# 或者使用列表推导式(最快)
result = [i for i in range(size)]
8. 与其他数据结构的转换
# 列表 ↔ 集合(去重)
numbers = [1, 2, 2, 3, 3, 3]
unique_numbers = list(set(numbers))
print(unique_numbers) # 输出: [1, 2, 3]
# 列表 ↔ 元组
tuple_data = tuple([1, 2, 3])
list_data = list((1, 2, 3))
# 列表 ↔ 字符串
text = ''.join(['h', 'e', 'l', 'l', 'o'])
chars = list("hello")
9. 实际应用示例
文件处理
# 读取文件内容到列表
def read_file_lines(filename):
try:
with open(filename, 'r', encoding='utf-8') as file:
return list(file.readlines())
except FileNotFoundError:
return []
# 处理CSV数据
csv_data = "name,age,city
Alice,25,Beijing
Bob,30,Shanghai"
lines = list(csv_data.split('
'))
headers = list(lines[0].split(','))
print("表头:", headers)
数据分析
# 数据分组统计
from collections import defaultdict
data = ['apple', 'banana', 'apple', 'orange', 'banana', 'apple']
count_dict = defaultdict(int)
for item in data:
count_dict[item] += 1
# 转换为排序后的列表
sorted_items = list(sorted(count_dict.items(), key=lambda x: x[1], reverse=True))
print("统计结果:", sorted_items)
10. 最佳实践
- 选择合适的方式:对于空列表,使用 [] 更简洁;对于从可迭代对象转换,使用 list() 更明确
- 注意性能:对于大型数据,思考使用生成器或迭代器
- 内存管理:及时释放不再需要的大型列表
- 类型安全:确保操作的对象是可迭代的
# 安全的列表创建函数
def safe_list_create(data, default=None):
"""安全创建列表"""
if default is None:
default = []
try:
return list(data)
except TypeError:
return default
# 使用示例
print(safe_list_create([1, 2, 3])) # 输出: [1, 2, 3]
print(safe_list_create(123)) # 输出: [](默认)
print(safe_list_create(123, [999])) # 输出: [999](自定义默认值)
总结
|
特性 |
描述 |
|
功能 |
创建列表对象 |
|
语法 |
list([iterable]) |
|
参数 |
任何可迭代对象 |
|
返回值 |
新列表对象 |
|
主要用途 |
数据转换、处理、存储 |
|
性能特点 |
比 [] 稍慢,但更灵活 |
|
适用场景 |
数据处理、算法实现、API交互 |
list() 是 Python 中最基础且最重大的函数之一,几乎在所有 Python 程序中都会用到。它提供了将各种数据转换为列表的灵活方式,是数据处理和算法实现的核心工具。
© 版权声明
文章版权归作者所有,未经允许请勿转载。
相关文章
暂无评论...
