Re: [問題] 有趣的問題 關於交集與聯集的處理方式

作者: darkgerm (黑駿)   2016-01-19 23:39:23
※ 引述《busystudent (busystudent)》之銘言:
: hi 我是Bob 第一次在這邊發文,聽說有不少高手臥虎藏龍!
: as title 我爬蟲了一個網站,經過整理得到很多如下面的結果
: ['spanish', 'web2.0', 'e-learning', 'education', 'social', 'spain', 'tools', 'learning', 'google', 'e-learning2.0']
: ['education', 'technology', 'learning', 'classroom', '%22educational%20technology%22', '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])

Links booklink

Contact Us: admin [ a t ] ucptt.com