Re: [問題] 如何將dict的values取set

看板Python作者 (cablin)時間13年前 (2012/02/20 21:46), 編輯推噓4(409)
留言13則, 2人參與, 最新討論串5/8 (看更多)
建議你把完整的code從頭到尾貼上來,或是直接找個空間上傳你的檔案 另外 (lambda x: set(x))==set (lambda x,y: x.intersection(y))==set.intersection 這裡用lambda非常多餘 加上set.intersection本身就可以接受多個參數 因此寫成set.intersection(*map(set, target.values()))就好 ※ 引述《kadodo (想辦法突破)》之銘言: : s=map(lambda x : set(x), target.values()) : print(reduce(lambda x,y: x.intersection(y), s)) : 以上這樣OK 有PRINT出正確結果 : s=map(lambda x : set(x), target.values()) : var_a = reduce(lambda x,y: x.intersection(y), s) : print(var_a) : 換成以上三行,想用一個變數去接 就會得到以下錯誤 : var_a = reduce(lambda x,y: x.intersection(y), s) : 錯誤訊息 : TypeError: reduce() of empty sequence with no initial value. : ※ 引述《kadodo (想辦法突破)》之銘言: : : 再請問一下 : : 我想用一個變數來接 : : var_a = reduce(lambda x,y: x.intersection(y), s) : : TypeError: reduce() of empty sequence with no initial value. : : 請問該如何解決? : : 我用Help去看 還是看不懂 : : reduce(function, sequence[, initial]) -> value : : Apply a function of two arguments cumulatively to the items of a sequence, : : from left to right, so as to reduce the sequence to a single value. -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 140.112.217.2

02/21 15:29, , 1F
請問set.intersection(*map(set, ds.values())) 這行是什麼
02/21 15:29, 1F

02/21 15:30, , 2F
意思呢? 尤其是那個*號
02/21 15:30, 2F

02/21 18:03, , 3F
f(a,b,c,...)==f(*(a,b,c,...))
02/21 18:03, 3F

02/21 18:14, , 4F
map前的*即是把map產生的iterator做unpack的動作
02/21 18:14, 4F

02/21 18:40, , 5F
請問我如果是要得到聯集怎麼寫? 先前討論是得到交集的寫法
02/21 18:40, 5F

02/21 19:37, , 6F
用set.union嗎?
02/21 19:37, 6F

02/21 21:08, , 7F
是的
02/21 21:08, 7F

02/21 21:10, , 8F
另外在一般的運算可以用&(交集)和|(聯集)等來寫
02/21 21:10, 8F

02/21 21:11, , 9F
set.__and__==set.intersection, set.__or__==set.union
02/21 21:11, 9F

02/21 22:45, , 10F
感謝幫忙 ~ 我會試試看
02/21 22:45, 10F

02/23 01:15, , 11F
另外,這裡如果有需要用lambda,那還不用comprehension
02/23 01:15, 11F

02/23 01:17, , 12F
真正要lambda的地方大概是讓常數有函式介面(變成常函式)
02/23 01:17, 12F

02/23 18:06, , 13F
更正,不如用comprehension
02/23 18:06, 13F
文章代碼(AID): #1FGaxFdt (Python)
文章代碼(AID): #1FGaxFdt (Python)