3. 使用列表/集合/字典
以下程式碼無先後順序 無連貫性
推薦影片教學頻道:
一、列表的使用
gg = "i am here~"
courses1 = ["Math", "History", "Physics", "Compute"]
courses2 = ["Art", "Life"]
nums = [1, 5, 10, 8, 7, 2]
len(courses1)
courses1.append(gg)
courses1.insert(2, gg)
courses1.extend(courses2)
courses1.append(courses2)
courses1.sort()
nums.sort()
nums.sort(reverse=True)
courses1.remove("Math")
courses1.pop(2)
max(nums)
min(nums)
courses1.index("History")
string = " - ".join(courses1)
二、集合的使用
- 集合通常是透過將列表轉換後取得
- 常用來判斷物件是否存在於列表中
language = ["Taiwanese", "English", "Chinese", "Japanese"]
I_can_say = ["Taiwanese", "English", "Taiwanese", "Portuguese"]
language = set(language)
I_can_say = set(I_can_say)
print("Taiwanese" in I_can_say)
print("Taiwanese" in set(I_can_say))
print(set(language).intersection(set(I_can_say)))
print(set(language).difference(set(I_can_say)))
print(set(language).union(set(I_can_say)))
三、字典的使用
dictionary = {"a":"apple", "b":"banana", 1:"this is 1", 2:"this is 2", "2":2}
dictionary["2"]
dictionary["a"]
dictionary[2]
dictionary.get("Am I Handsome?", "Not Found")
students = {
"John" : {
"name" : "John",
"age" : 17,
"gender" : "male",
"working" : False,
"habbits" : ["basket ball", "soccer", "tennis"],
"grade" : "second-grade"
},
"Alice" : {
"name" : "Alice",
"age" : 16,
"gender" : "female",
"working" : False,
"habbits" : ["chess", "tennis"],
"grade" : "first-grade"
},
"Keven" : {
"name" : "Keven",
"age" : 18,
"gender" : "male",
"working" : True,
"habbits" : ["basket ball", "tennis", "jogging"],
"grade" : "third-grade"
},
"Jarvis" : {
"name" : "Jarvis",
"age" : 18,
"gender" : "male",
"working" : True,
"grade" : "third-grade"
}
}
for name in students.keys():
if "habbits" in students[name].keys():
print(name, "habbits", True)
else:
print(name, "habbits", False)
進階例子中 我們舉例有四位學生 John Alice Keven Jarvis
用字典 並用下面提供的迴圈 (下一篇會詳細介紹)
就可以尋找是否有人缺少資料
此例子中 學生 Jarvis 缺少興趣資料 habbits
所以會輸出 Jarvis habbits False
3. 使用列表/集合/字典
tags:
Python
以下程式碼無先後順序 無連貫性
推薦影片教學頻道:
一、列表的使用
二、集合的使用
三、字典的使用
上一篇
下一篇