# ===== CodeLab: Python 列表与字典实战 =====
# 来源: https://aoerliang.dpdns.org/articles/python-lists-dicts
# 以下代码片段按文章出现顺序拼接, 共 6 段

# ----- 片段 1 (python) -----
tasks = ["写代码", "测试", "部署"]
tasks.append("维护")          # 末尾添加
tasks.insert(1, "评审")       # 指定位置插入
tasks.remove("测试")          # 按值删除(只删第一个)
last = tasks.pop()            # 弹出末尾并返回
first = tasks.pop(0)          # 弹出指定下标
print(tasks)                  # ['写代码', '评审', '部署']
print("部署" in tasks)
print(len(tasks))

# ----- 片段 2 (python) -----
nums = [0, 1, 2, 3, 4, 5]
print(nums[1:4])     # [1, 2, 3] 含头不含尾
print(nums[:3])      # [0, 1, 2]
print(nums[::2])     # [0, 2, 4] 隔一个取一个
print(nums[::-1])    # [5, 4, 3, 2, 1, 0] 反转

# 三种拷贝方式
copy1 = nums[:]
copy2 = nums.copy()
copy3 = list(nums)

# 注意:嵌套列表的浅拷贝只复制外层
matrix = [[1, 2], [3, 4]]
shallow = matrix[:]
shallow[0][0] = 99
print(matrix)        # [[99, 2], [3, 4]] 内层被改了!

# ----- 片段 3 (python) -----
scores = [88, 72, 95, 61, 88]
scores.sort()               # 原地升序
print(scores)               # [61, 72, 88, 88, 95]

# 不修改原列表的排序
sorted_scores = sorted(scores, reverse=True)
print(sorted_scores)        # [95, 88, 88, 72, 61]

# 去重:转 set 再转回 list
unique = list(set(scores))
print(unique)               # [72, 88, 95, 61] 顺序不保证

# ----- 片段 4 (python) -----
user = {"name": "Ada", "age": 18}
user["city"] = "北京"          # 新增键
user["age"] = 19              # 修改已有键
del user["city"]              # 删除键

# get:键不存在时返回默认值,不报错
age = user.get("age", 0)      # 19
email = user.get("email", "未填写")   # 未填写

# 合并两个字典
user.update({"hobby": "coding", "age": 20})
print(user)

# ----- 片段 5 (python) -----
stock = {"苹果": 5, "香蕉": 12, "橙子": 0}

for key in stock:                 # 默认遍历键
    print(key)

for key, value in stock.items():  # 键值对
    print(f"{key}: {value}")

for value in stock.values():      # 只取值
    print(value)

# 条件筛选:库存不足的水果
low = [k for k, v in stock.items() if v == 0]
print(low)   # ['橙子']

# ----- 片段 6 (python) -----
text = "python code data python code python"
words = text.split()

freq = {}
for w in words:
    freq[w] = freq.get(w, 0) + 1   # 等价于 if/else 计数

# 按出现次数从高到低排序
ranking = sorted(freq.items(), key=lambda x: x[1], reverse=True)
print(ranking)   # [('python', 3), ('code', 2), ('data', 1)]

# 用 collections.Counter 一行搞定
from collections import Counter
print(Counter(words).most_common(2))
