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

看板Python作者 (黑駿)時間9年前 (2016/01/19 15:39), 編輯推噓0(000)
留言0則, 0人參與, 最新討論串3/3 (看更多)
※ 引述《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]) -- 光明 的背後 是 黑暗 黑暗 的背後 還是 黑暗 由此可知 黑暗 > 光明 Q.E.D. -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 140.113.235.135 ※ 文章網址: https://www.ptt.cc/bbs/Python/M.1453217965.A.492.html
文章代碼(AID): #1MdbYjII (Python)
討論串 (同標題文章)
文章代碼(AID): #1MdbYjII (Python)