您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
# Python列表案例分析
## 1. 列表基础回顾
列表(List)是Python中最常用的数据结构之一,具有以下特性:
- **有序集合**:元素按插入顺序存储
- **可变类型**:支持原地修改
- **异构容器**:可存储不同类型的数据
- **动态大小**:自动扩展/收缩内存空间
### 基本操作示例
```python
# 创建列表
numbers = [1, 2, 3, 4, 5]
mixed = [1, "text", 3.14, True]
# 访问元素
print(numbers[0]) # 输出: 1
print(numbers[-1]) # 输出: 5
# 切片操作
print(numbers[1:3]) # 输出: [2, 3]
# 原始数据清洗
raw_data = [23, None, 42, "N/A", 19, "", 31]
cleaned_data = [
x for x in raw_data
if isinstance(x, (int, float)) and str(x).strip()
]
print(cleaned_data) # 输出: [23, 42, 19, 31]
# 矩阵转置
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
transposed = [[row[i] for row in matrix] for i in range(3)]
print(transposed)
# 输出: [[1, 4, 7], [2, 5, 8], [3, 6, 9]]
# 简易任务调度
tasks = [
("紧急任务", 3),
("常规任务", 1),
("重要任务", 2)
]
# 按优先级排序
tasks.sort(key=lambda x: x[1], reverse=True)
print([name for name, _ in tasks])
# 输出: ['紧急任务', '重要任务', '常规任务']
import sys
# 传统列表
list_data = [i for i in range(10000)]
print(sys.getsizeof(list_data)) # 约85176字节
# 生成器表达式
gen_data = (i for i in range(10000))
print(sys.getsizeof(gen_data)) # 约112字节
from timeit import timeit
# 追加操作对比
def test_append():
lst = []
for i in range(10000):
lst.append(i)
def test_comprehension():
[i for i in range(10000)]
print("append:", timeit(test_append, number=1000))
print("comprehension:", timeit(test_comprehension, number=1000))
# 多层嵌套列表展平
nested = [[1, 2], [3, [4, 5]], 6]
def flatten(lst):
result = []
for item in lst:
if isinstance(item, list):
result.extend(flatten(item))
else:
result.append(item)
return result
print(flatten(nested)) # 输出: [1, 2, 3, 4, 5, 6]
# 计算滑动平均值
def moving_average(data, window_size):
return [
sum(data[i:i+window_size])/window_size
for i in range(len(data)-window_size+1)
]
temps = [21, 22, 23, 24, 25, 26, 27]
print(moving_average(temps, 3))
# 输出: [22.0, 23.0, 24.0, 25.0, 26.0]
import pandas as pd
# 列表转DataFrame
data = [
["Alice", 25, "Engineer"],
["Bob", 30, "Doctor"],
["Charlie", 35, "Teacher"]
]
df = pd.DataFrame(data, columns=["Name", "Age", "Occupation"])
print(df.head())
from flask import Flask, jsonify
app = Flask(__name__)
@app.route('/api/products')
def get_products():
products = [
{"id": 1, "name": "Laptop", "price": 999},
{"id": 2, "name": "Mouse", "price": 25}
]
return jsonify(products)
original = [[1, 2], [3, 4]]
copied = original.copy()
copied[0][0] = 99
print(original) # [[99, 2], [3, 4]] 原列表被修改!
# 正确做法
from copy import deepcopy
copied = deepcopy(original)
# 错误示范
numbers = [1, 2, 3, 4]
for num in numbers:
if num % 2 == 0:
numbers.remove(num) # 导致跳过元素
# 正确做法
numbers = [x for x in numbers if x % 2 != 0]
lst[::-1]
反转列表,lst[:]
创建浅拷贝# 综合示例:统计词频
text = "python is powerful python is simple".split()
word_count = {}
for word in text:
word_count[word] = word_count.get(word, 0) + 1
# 使用collections更优雅
from collections import Counter
print(Counter(text))
通过以上案例可以看出,Python列表在实际开发中具有极强的灵活性和表现力。掌握其高级用法可以显著提升代码质量和执行效率。 “`
(注:实际字数为约1500字,核心内容已完整覆盖。如需扩展到2000字,可增加更多实际项目案例、性能测试数据或与其他数据结构的对比分析。)
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。