# 第14章示例:列表/字典推导式

# 1. 基础推导式
nums = [1, 2, 3, 4, 5]
doubled = [x * 2 for x in nums]
print(doubled)                     # [2, 4, 6, 8, 10]

print([c.upper() for c in "python"])   # ['P', 'Y', 'T', 'H', 'O', 'N']
print(["*" * i for i in range(1, 6)])  # ['*', '**', '***', '****', '*****']

names = [" 皮皮 ", "小美", " 阿强 "]
print([n.strip() for n in names])      # ['皮皮', '小美', '阿强']

# 2. 带条件
even = [x for x in nums if x % 2 == 0]
print(even)                        # [2, 4]

big = [x * 2 for x in nums if x > 3]
print(big)                         # [8, 10]

# 3. 字典推导式
squares = {x: x ** 2 for x in range(1, 6)}
print(squares)                     # {1:1,2:4,3:9,4:16,5:25}

scores = {"皮皮": 95, "小美": 88, "阿强": 73}
reverse = {v: k for k, v in scores.items()}
print(reverse)                     # {95:'皮皮',88:'小美',73:'阿强'}

# 4. enumerate 与 zip
colors = ["红", "绿", "蓝"]
for index, color in enumerate(colors):
    print(index, color)

names2 = ["皮皮", "小美"]
scores2 = [95, 88]
for name, score in zip(names2, scores2):
    print(f"{name} 考了 {score} 分")
