作者yauhh (喲)
看板Python
標題Re: [問題] 搜尋 nested list 中的字串
時間Sat Oct 25 13:50:07 2014
※ 引述《hohiyan (海洋)》之銘言:
: 大家好
: 我目前正在自學python,想請教是否有更好的方法來處理搜尋nested list中的資料。
: 例如一個 nested list 為 ft = [['a',10],['b',5],['c',11'],['d',3]]
: 題目為
: Function add() takes a single-character string and a ft, and modified the ft
: to increase the number of occurrences of that character by 1.
: 例如 add('a',ft) 會 return ft = [['a',11],['b',5],['c',11'],['d',3]]
: 而 add('i',ft) return ft = [['a',10],['b',5],['c',11'],['d',3],['i',1]]
要很快找到文字的次數,不要用 list 而要用 dictionary 就可以了。
list 是比較原始,方便循序搜尋的資料格式,而 dictionary 則是用標籤快速
尋找的格式。
ft = {'a':10, 'b':5, 'c':11, 'd':3}
def occur(x, ft):
return x in list(ft)
def add(x, ft):
if occur(x, ft):
ft.update({x: ft[x]+1})
else:
ft.update({x: 1})
return ft
我目前所理解的 dictionary ,大概是這樣:假設 ft 是 dictionary ,
dictionary 是一堆 key 對應到一堆 value ,有點像函數。
用 list(ft) 可以取出 ft 的 keys , keys 中每個東西是獨一的。
另外,用 ft.update({k1: v1, k2: v2}) 可以直接把 ft 中的 k1 和 k2
的對應值洗掉。
所以如果要讓對應值一直往上加,要先從 ft 把舊的對應值很快抓出來,
然後,根據舊的對應值修改為新的對應值,再洗回去。
dictionary 抓對應值的速度是 O(1) ,洗回去的速度也是 O(1) 。
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 118.168.168.133
※ 文章網址: http://webptt.com/m.aspx?n=bbs/Python/M.1414216211.A.3D8.html
※ 編輯: yauhh (118.168.168.133), 10/25/2014 14:40:42
1F:推 hohiyan: 謝謝!我現在的進度到dictionary了,用dict做真的快很多 10/26 00:48
2F:→ YONIQ: occur 不要在用 list 包,有搜尋需要的話用 dict, set 10/27 05:46
3F:→ YONIQ: 搜尋 list 要遍歷元素直到找到 10/27 05:49
4F:推 bigpigbigpig: occur() 可以改成: 10/27 06:26
5F:→ bigpigbigpig: def occur(x, ft): return x in ft 10/27 06:26
6F:推 bigpigbigpig: add() 可以改成: 10/27 06:50
7F:→ bigpigbigpig: def add(x, ft): 10/27 08:07
8F:→ bigpigbigpig: ft[ch] = ft.get(ch, 0) + 1 10/27 08:07
9F:→ bigpigbigpig: return ft 10/27 08:07
10F:→ bigpigbigpig: ft[x] = ft.get(x, 0) + 1 <== 前兩行改成這樣 10/27 08:08
11F:→ yauhh: 沒關係,我不急,用list就好了 10/27 21:14
12F:→ yauhh: 我很受不了有些人那種沒來由的著急,什麼都要最快 10/27 21:15
13F:→ yauhh: 我實務上在dictionary中一用就在裡頭放了超過6000個物件, 10/28 08:27
14F:→ yauhh: 寫 in list(ft) 只是求個字面上,反應我對這個物件的理解 10/28 08:28
15F:→ yauhh: 使用上沒有多大的障礙。 10/28 08:28
而且, ft[x] 是 O(1) , keys(ft) 難道也是 O(1) 嗎? 我的判斷,要嘛要寫
x in keys(ft) 要嘛則寫 x in list(ft) ,有什麼不同?或者說是 in list(ft) 就O(n)
而 in set(ft) 則O(k), k < n ,有這樣的差別嗎?
至於取值的部分,我照樣用 ft[x] ,沒有所謂該用 list 或 dict 包不包的問題。
16F:→ yauhh: 而bigpigbigpig,你的建議,我覺得最終只反映到程式會比較 10/28 08:29
17F:→ yauhh: 短,但是我好好寫 if-else ,程度不同的同事可以看得懂, 10/28 08:30
18F:→ yauhh: 這是好處。我既然沒有問題,就不必忙著來幫我解題。 10/28 08:30
※ 編輯: yauhh (118.168.161.23), 10/28/2014 08:36:49
※ 編輯: yauhh (118.168.161.23), 10/28/2014 08:39:42