Python 数据处理 “偷懒” 技巧:基础进阶小玩法,效率翻倍

17 阅读2分钟

还在手动抠数据格式?这 3 个进阶偏基础的小技巧,用基础语法玩出花,日常处理列表、字典数据直接省一半时间!

1. 字典推导式:一行生成字典,比 for 循环香多了

列表推导式大家都熟,但字典推导式才是处理键值对的 “懒人神器”,一行搞定映射关系,不用再 dict[key] = value 慢慢填!

# 需求1:将列表元素作为键,索引作为值
fruits = ["apple", "banana", "orange"]

# 传统写法:循环+赋值
fruit_dict = {}
for idx, fruit in enumerate(fruits):
    fruit_dict[fruit] = idx
print(fruit_dict)  # {'apple': 0, 'banana': 1, 'orange': 2}

# 字典推导式:一行搞定
fruit_dict_pro = {fruit: idx for idx, fruit in enumerate(fruits)}
print(fruit_dict_pro)  # 结果同上

# 需求2:筛选字典中值大于10的键值对
score = {"math": 95, "chinese": 88, "english": 100, "art": 9}
high_score = {k: v for k, v in score.items() if v > 90}
print(high_score)  # {'math': 95, 'english': 100}

2. sorted() 高级排序:按自定义规则排序列表 / 字典

默认的 sorted() 只能按元素本身排序,但加上 key 参数,就能实现按长度、按属性、按自定义函数排序,灵活到离谱!

# 需求1:按字符串长度排序
words = ["python", "java", "go", "javascript", "c"]
sorted_by_len = sorted(words, key=lambda x: len(x))
print(sorted_by_len)  # ['c', 'go', 'java', 'python', 'javascript']

# 需求2:按元组的第二个元素排序
students = [("小明", 85), ("小红", 92), ("小刚", 78)]
sorted_by_score = sorted(students, key=lambda x: x[1], reverse=True)
print(sorted_by_score)  # [('小红', 92), ('小明', 85), ('小刚', 78)]

# 需求3:按字典的值排序
score = {"math": 95, "chinese": 88, "english": 100}
# 先转成键值对列表,再排序
sorted_score = sorted(score.items(), key=lambda x: x[1])
print(dict(sorted_score))  # {'chinese': 88, 'math': 95, 'english': 100}

3. any()/all() 进阶:搭配生成器表达式,高效判断

直接用 any()/all() 搭配生成器表达式,比列表推导式更省内存(不用生成完整列表),判断大批量数据时速度更快!

# 需求1:判断列表是否有负数(生成器表达式版)
nums = [1, 3, 5, -2, 7, 9]
has_negative = any(num < 0 for num in nums)
print(has_negative)  # True

# 需求2:判断字典所有值都是正数
data = {"a": 10, "b": 20, "c": 5}
all_positive = all(v > 0 for v in data.values())
print(all_positive)  # True

# 对比:生成器 vs 列表推导式
# 生成器:按需生成,不占内存
# 列表推导式:生成完整列表,占内存
import sys
gen = (num < 0 for num in nums)
lst = [num < 0 for num in nums]
print(sys.getsizeof(gen))  # 小,几十字节
print(sys.getsizeof(lst))  # 大,上百字节

小总结

  1. 字典推导式是生成 / 筛选字典的 “快捷指令”,一行顶三行;
  2. sorted() 加 key 参数,能实现任意规则的排序;
  3. any()/all() 搭配生成器表达式,判断数据更省内存。