[問題] 關於重複搜尋

看板Python作者 (ppoo)時間6年前 (2017/08/23 07:15), 編輯推噓0(006)
留言6則, 2人參與, 最新討論串1/1
小弟最近在做PYTHON習題 Problem Given: A string ss of length at most 10000 letters. Return: The number of occurrences of each word in ss, where words are separated by spaces. Words are case-sensitive, and the lines in the output can be in any order. Sample Dataset: We tried list and we tried dicts also we tried Zen Sample Output: and 1 We 1 tried 3 dicts 1 list 1 we 2 also 1 Zen 1 但是小弟做同樣練習時會重複出現有重複的字: we 3 -------1st occured tried 3-------1st occured list 1 and 1 we 3-------2nd occured tried 3-------2nd occured dicts 1 also 1 we 3------3rd occured tried 3------3rd occured zen 1 以下為小弟的CODE,再請各位大大幫忙檢視一下問題出在哪裡了。謝謝! lines = 'We tried list and we tried dicts also we tried Zen' for word in lines.lower().split(' '): pare = {word: lines.lower().count(word)} pare.update(pare) #希望用update消除重複項 for k1, v1 in pare.items(): print(k1, v1) -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 96.224.226.89 ※ 文章網址: https://www.ptt.cc/bbs/Python/M.1503443731.A.CF0.html

08/23 11:19, , 1F
word那個回圈每次都會重製你的pare所以根本沒紀錄到
08/23 11:19, 1F

08/23 11:25, , 2F
迴圈外面宣告一個dup = dict()
08/23 11:25, 2F

08/23 11:25, , 3F
然後dup.update(pare)
08/23 11:25, 3F

08/23 11:26, , 4F
最後那個迴圈就直接搬出來不要在迴圈裡面pare換成dup
08/23 11:26, 4F

08/23 11:27, , 5F
然後他題目大小寫應該市分開算lower()要拿掉
08/23 11:27, 5F

08/24 10:35, , 6F
{k: lines.count(k) for k in set(lines.split())}
08/24 10:35, 6F
文章代碼(AID): #1PdBiJpm (Python)