Files
2025PY/day24/09-函数和数据容器的练习.py
2025-05-22 16:50:44 +08:00

98 lines
3.1 KiB
Python

# 1. 列表筛选与转换
# 定义函数 filter_and_square(lst),筛选出列表中的偶数,返回每个数的平方。
# 示例输入:[1, 2, 3, 4, 5, 6] → 输出:[4, 16, 36]
def filter_and_square(lst):
return [x ** 2 for x in lst if x % 2 == 0]
# 示例调用
print(filter_and_square([1, 2, 3, 4, 5, 6])) # 输出: [4, 16, 36]
# 2. 字典值求和
# 定义函数 sum_dict_values(dicts),计算多个字典中所有值的总和。
def sum_dict_values(dicts):
total = 0
for dictionary in dicts:
for value in dictionary.values():
total += value
return total
# 3. 嵌套列表扁平化
# 定义函数 flatten(lst),将任意深度的嵌套列表展开为一维列表。
# 示例输入:[1, [2, [3, 4], 5], 6] → 输出:[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([1, [2, [3, 4], 5], 6])) # 输出: [1, 2, 3, 4, 5, 6]
# 4. 统计单词频率
# 定义函数 word_count(text),统计字符串中每个单词的出现次数(忽略大小写)。
# 示例输入:"Hello world! Hello Python." → 输出:{'hello': 2, 'world': 1, 'python': 1}
from collections import Counter
import re
def word_count(text):
# 提取单词(忽略大小写,按非字母分割)
words = re.findall(r'\b\w+\b', text.lower())
return dict(Counter(words)) # 转换为字典
# 示例调用
text = "Hello world! Hello Python."
print(word_count(text)) # 输出: {'hello': 2, 'world': 1, 'python': 1}
# 5. 集合交集与并集
# 定义函数 process_sets(sets),返回所有集合的交集和并集。
# 示例输入:[{1, 2, 3}, {2, 3, 4}, {3, 4, 5}] → 输出:({3}, {1, 2, 3, 4, 5})
def process_sets(sets):
if not sets:
return (set(), set())
intersection = set.intersection(*sets) # 交集
union = set.union(*sets) # 并集
return (intersection, union)
# 示例调用
sets = [{1, 2, 3}, {2, 3, 4}, {3, 4, 5}]
print(process_sets(sets)) # 输出: ({3}, {1, 2, 3, 4, 5})
# 6. 字典按值排序
# 定义函数 sort_dict_by_value(d),返回按值升序排序的键值对列表。
# 示例输入:{'a': 3, 'b': 1, 'c': 2} → 输出:[('b', 1), ('c', 2), ('a', 3)]
def sort_dict_by_value(d):
return sorted(d.items(), key=lambda item: item[1]) # 按值升序排序
# 示例调用
d = {'a': 3, 'b': 1, 'c': 2}
print(sort_dict_by_value(d)) # 输出: [('b', 1), ('c', 2), ('a', 3)]
# 7. 列表分组
# 定义函数 group_by(lst, key_func),根据指定函数的返回值对列表元素进行分组。
from collections import defaultdict
def group_by(lst, key_func):
groups = defaultdict(list)
for item in lst:
key = key_func(item)
groups[key].append(item)
return dict(groups) # 转换为普通字典
# 示例调用
lst = [1, 2, 3, 4, 5]
key_func = lambda x: 'even' if x % 2 == 0 else 'odd'
print(group_by(lst, key_func)) # 输出: {'odd': [1, 3, 5], 'even': [2, 4]}