接續昨天的基本語法,今天將主要集中在「集合」的內容整理。
範例程式主要來自於W3Schools。
Python中四種集合,以下為四種集合的簡單比較:
類型 | 是否有順序(註1) | 內容是否可改變 | 內部元素是否可重複 |
---|---|---|---|
List | Y | Y | Y |
Tuple | Y | N | Y |
Set | N | N(註2) | N |
Dictionary | Y(註3) | Y | N(註4) |
註1:有順序意味著可以使用index進行存取。
註2:Set內部元素不可直接修改,但可以新增和刪除。
註3:Python 3.7後才有順序性,Python 3.6前都是無順序性。
註4:內部元素重複出現時系統不會報錯,但是會以「後蓋前」的方式設定數值。
mylist1 = ["apple", "banana", "cherry"]
mylist2 = list(("apple", "banana", "cherry"))
note = "改變的元素數量 {} 指派的元素數量: {}"
# 改變的元素數量 = 指派的元素數量
thislist = ["apple", "banana", "cherry", "orange"]
thislist[1:3] = ["blackcurrant", "watermelon"]
print(note.format("=", thislist))
# 改變的元素數量 < 指派的元素數量
thislist = ["apple", "banana", "cherry", "orange"]
thislist[1:2] = ["blackcurrant", "watermelon"]
print(note.format("<", thislist))
# 改變的元素數量 > 指派的元素數量
thislist = ["apple", "banana", "cherry", "orange"]
thislist[1:3] = ["blackcurrant"]
print(note.format(">", thislist))
Output:
改變的元素數量 = 指派的元素數量: ['apple', 'blackcurrant', 'watermelon', 'orange']
改變的元素數量 < 指派的元素數量: ['apple', 'blackcurrant', 'watermelon', 'cherry', 'orange']
改變的元素數量 > 指派的元素數量: ['apple', 'blackcurrant', 'orange']
thislist = ["apple", "banana", "cherry", "orange"]
thislist.insert(2,"blackcurrant")
print(thislist)
thislist = ["apple", "banana", "cherry", "orange"]
thislist.append("blackcurrant")
print(thislist)
# 合併兩個list (使用extend)
thislist = ["apple", "banana", "cherry", "orange"]
otherlist = ["blackcurrant", "pineapple"]
thislist.extend(otherlist)
print(thislist)
# 合併兩個list (使用 + )
thislist = ["apple", "banana", "cherry", "orange"]
otherlist = ["blackcurrant", "pineapple"]
finallist = thislist + otherlist
print(finallist)
# 合併tuple到list
thislist = ["apple", "banana", "cherry", "orange"]
othertuple = ("blackcurrant", "pineapple")
thislist.extend(othertuple)
print(thislist)
# 無視大小寫進行排序
thislist = ["banana", "Orange", "Kiwi", "cherry"]
thislist.sort(key = str.lower)
print(thislist)
mytuple1 = ("apple", "banana", "cherry")
mytuple2 = tuple(("apple", "banana", "cherry"))
# 建立僅含單一元素的tuple
mytuple3 = ("apple",)
改變Tuple:Tuple本身不可變動,但可藉由將Tuple轉換成List進行變動後再重新轉換回Tuple以達到目的。
計算Tuple內特定元素出現的次數:tuple.count(value)
thistuple = ["apple", "banana", "apple", "orange"]
print(thistuple.count("apple"))
thistuple = ["apple", "banana", "apple", "orange"]
print(thistuple.index("apple"))
myset1 = {"apple", "banana", "cherry"}
myset2 = set(("apple", "banana", "cherry"))
# 建立僅含單一元素的tuple
mytuple3 = ("apple",)
thisset = {"apple", "banana", "cherry"}
# 印出set內所有元素
for x in thisset:
print(x)
# 判斷banana是否存在set
print("banana" in thisset)
dict = {
"id":1,
"name":"Alice",
"age":25
}
print(dict)
取得Dictionary中所有元素的名稱:dict.keys()
取得Dictionary中所有元素數值:dict.values()
新增元素/ 變更原有元素數值
dict = {
"id":1,
"name":"Alice",
"age":25
}
dict["age"] = 27
print(dict)
dict.update({"age":24})
print(dict)