重點:list、dict、set 的使用與資料組織方式
練習:畫出資料結構示意圖
fruits = ["蘋果", "香蕉", "芒果"]
print(fruits)
numbers = [1, 2, 3, 4]
print("第一個數字:", numbers[0])
colors = ["紅", "綠", "藍"]
colors.append("黃")
print(colors)
scores = [80, 90, 100]
print("平均分:", sum(scores) / len(scores))
animals = ["貓", "狗", "鳥"]
for animal in animals:
print("我喜歡", animal)
nums = [10, 20, 30, 40, 50]
print(nums[1:4])
letters = ["a", "b", "c", "d"]
for i in range(len(letters)):
print(i, letters[i])
names = ["會安", "小明", "小美"]
print(names[-1])
person = {"姓名": "會安", "年齡": 30}
print(person["姓名"])
scores = {"國文": 90, "英文": 85}
scores["數學"] = 95
print(scores)
info = {"name": "會安", "city": "台北"}
for key in info:
print(key, ":", info[key])
student = {"姓名": "小美", "分數": 88}
print("是否有分數欄位:", "分數" in student)
grades = {"甲": 90, "乙": 80, "丙": 70}
print(grades.get("丁", "查無成績"))
data = {"a": 1, "b": 2}
data.update({"c": 3})
print(data)
info = {"name": "會安", "age": 30}
info.pop("age")
print(info)
scores = {"國文": 90, "英文": 85}
for subject, score in scores.items():
print(subject, "成績:", score)
colors = {"紅", "綠", "藍"}
print("紅" in colors)
nums = {1, 2, 3}
nums.add(4)
print(nums)
fruits = {"蘋果", "香蕉", "蘋果"}
print(fruits)
set1 = {1, 2, 3}
set2 = {3, 4, 5}
print(set1 & set2)
students = [
{"name": "會安", "score": 90},
{"name": "小明", "score": 80}
]
for s in students:
print(s["name"], ":", s["score"])
inventory = {"蘋果": 5, "香蕉": 3}
inventory["芒果"] = 7
for fruit, qty in inventory.items():
print(fruit, "數量:", qty)
data = {
"姓名": "會安",
"興趣": ["閱讀", "程式", "旅行"]
}
print(data["興趣"][1])
scores = [
{"科目": "國文", "分數": 90},
{"科目": "英文", "分數": 85}
]
total = sum([s["分數"] for s in scores])
print("總分:", total)
students = {
"會安": {"國文": 90, "英文": 85},
"小明": {"國文": 80, "英文": 88}
}
for name, subjects in students.items():
print(name, "英文成績:", subjects["英文"])
tags = {"Python", "AI", "教育"}
tags.add("學習")
tags.remove("AI")
print(tags)
shopping_list = ["蘋果", "香蕉", "蘋果", "芒果"]
unique_items = set(shopping_list)
print("不重複項目:", unique_items)
data = {
"姓名": "會安",
"技能": {"Python", "HTML", "JS"}
}
print("是否會 JS:", "JS" in data["技能"])