關於交集與聯集的處理方式
大家好
我在網站上自學python時
經過整理得到下面的結果
['spanish', 'web2.0', 'e-learning', 'education', 'social', 'spain', 'tools', '
learning', 'google', 'e-learning2.0']
['education', 'technology', 'learning', 'classroom', '22educational20technol
ogy22', 'google', 'teaching', 'collaboration', 'students', 'web2.0']
[education]
[technology]
每一個list就是一個人所收藏的標籤
A收藏第一行的list標籤集,B收藏第二行的標籤集等,有很多筆list
我想問,要如何計算與判斷同時收藏education標籤與technology的人數
以及要如行計算與判斷收藏education或收藏technology的人數
我一開始是打算先指定一個標籤education
再使用if判斷是否與目標technology同時出現
可是考慮到人數就又感覺到怪怪的
請大家給我一點提示! 謝謝
要判斷 "同時收藏 education 及 technology" / "有收藏 education 或 echnology"
建意可以用 set 來做
data = [
['spanish', 'education', 'e-learning', ...],
['education', 'technology', 'learning', ...],
['education'],
['technology],
]
# 如果 data 本來不是 set,可以先轉成 set
# 沒特別需求的話,建意一開始就存成 set
data = [set(i) for i in data]
# 計算 "同時收藏 education 及 technology" (屬於 ∈)
count = 0
for i in data:
if {'education', 'technology'} <= i:
count += 1
# 熟悉 functional programming 的話也可以這樣寫
count = len([i for i in data if {'education', 'technology'} <= i])
# 計算 "有收藏 education 或 technology" (交集 ∩)
count = 0
for i in data:
if {'education', 'technology'} & i:
count += 1
# 同樣也可以這樣寫
count = len([i for i in data if {'education', 'technology'} & i])