Files
python/20-24/lianxi-enumerate.py
2026-05-06 11:21:42 +08:00

88 lines
2.4 KiB
Python

# enumerate()函数的基本概念
# enumerate()是Python的内置函数,用于将一个可迭代对象(如列表、元组、字符串等)组合成一个带索引的序列。 它返回一个枚举对象,该对象包含索引和对应的值,使得我们可以在循环中同时获取元素的索引和值。
# enumerate()函数的主要作用是解决在遍历可迭代对象时需要同时获取索引和值的常见需求,避免手动维护索引计数器。
# 数组结合
items = ["苹果", "香蕉", "橙子", "葡萄"]
for index, val in enumerate(items):
print(f"{index}:{val}")
# 字符串
text = "Hello"
for index, s in enumerate(text):
print(f"{index}:{s}")
# 元组
coordinates = [(10, 20), (30, 40), (50, 60), (70, 80)]
for index, (x, y) in enumerate(coordinates):
print(f"{index}:x-{x}y-{y}")
scores = {"数学": 95, "英语": 88, "物理": 92, "化学": 90}
for index, (key, val) in enumerate(scores.items()):
print(f"{index}:{key}:{val}")
# 与其他内置函数结合
# zip()
names = ["张三", "李四", "王五"]
ages = [25, 30, 28]
cities = ["北京", "上海", "广州"]
for index, (name, ages, cities) in enumerate(zip(names, ages, cities)):
print(f"{index}:name:{name},age:{ages},cities:{cities}")
# 与filter()函数结合使用
# 过滤偶数
list_arr = [1, 2, 3, 4, 5]
new_list = filter(lambda x: x % 2 == 0, list_arr)
for index, val in enumerate(new_list):
print(f"{index}:{val}")
# 与map()函数结合使用
words = ["hello", "world", "python", "programming"]
upper_words = map(lambda s: s.upper(), words)
# print(list(upper_words))
for index, val in enumerate(upper_words):
print(f"{index}:{val}")
# 场景
# 创建带索引的字典
items = ["苹果", "香蕉", "橙子", "葡萄"]
indexed_dict = {index: item for index, item in enumerate(items)}
print(indexed_dict)
for key, val in indexed_dict.items():
print(f"{key}:{val}")
# 查找元素的位置
def find_all_potions(lst, target):
position = [index for index, val in enumerate(lst) if val == target]
return position
fruits = ["苹果", "香蕉", "橙子", "葡萄", "香蕉", "苹果"]
banana_positions = find_all_potions(fruits, "香蕉")
print(banana_positions)
# 条件计数
scores = [85, 92, 78, 96, 88, 91, 87, 94]
filter_scores = []
for i, scorce in enumerate(scores):
if scorce > 90:
filter_scores.append({i: scorce})
print(filter_scores)