Python 集合(三)

用書 PYTHON王者歸來 作者洪錦魁

練習一

假如一個班有八人,四個參加康輔社,兩個參加音樂社,列出

1.同時參加康輔社和音樂社的人

2.沒有參加社團的人

# 假如一個班有八人,四個參加康輔社,兩個參加音樂社,列出
# 1.同時參加康輔社和音樂社的人
# 2.沒有參加社團的人
Class ={"Susan","Kiki","Nini","Aaby","Lucy","Can","Alie","Miku"}
sport ={"Nini","Aaby","Lucy","Can"}
music ={"Susan","Kiki","Nini","Aaby"}
twoclub = sport & music
noclub  = Class - (sport | music)
print(f"同時參加康輔社和音樂社的人{twoclub}")
print(f"沒有參加社團的人{noclub}")

執行結果

練習二 集合的生成式

number = {n for n in range(1,30,5)}
print(number)
print(type(number))
number1 = {n for n in range(1,30,5) if n % 2 ==0}
print(number1)
print(type(number1))

執行結果

練習三 增加程式效率

for applejuice in word

若是要找 applejuice的 e 或是 p被執行幾次,

我們如果用 for applejuice in word 去尋找,

那會各處理兩次(因為有兩個)

因為集合不會有相同元素,所以只要處理一次幾就好。

for applejuice in set(word)

word = "applejuice"
wordcount ={w:word.count(w)  for w in set(word)}
print(wordcount)

執行結果

練習四特調

drinks = {
    "milk_tea":{"milk","black_tea","sugar"},
    "lemon_tea":{"lemon","black_tea","sugar"},
    "fruit_tea":{"lemon","pinapple","green_tea","sugar"},
    "Dodo_tea":{"lemon","Dodo","green_tea","sugar"},
    "tapioka_milk_tea":{"tapioka","milk","black_tea","sugar"}

}
#列出有含牛奶的飲料
print("列出有含牛奶的飲料")
for name,formulas in drinks.items():
    if "milk" in formulas:
        print(name)
#列出有含檸檬的飲料
print("列出有含檸檬的飲料")
for name,formulas in drinks.items():
    if "lemon" in formulas:
        print(name)
#列出有含檸檬,但不含紅茶的飲料
print("列出有含檸檬,但不含紅茶的飲料")
for name,formulas in drinks.items():
    if "lemon" in formulas and not("black_tea" in formulas):
        print(name)
#列出有含檸檬,但不含多多和紅茶的飲料
print("列出有含檸檬,但不含多多和紅茶的飲料")
for name,formulas in drinks.items():
    if "lemon" in formulas and not formulas & {"black_tea","Dodo"}:
        print(name)

執行結果