Re: [問題] 搜尋 nested list 中的字串

看板Python作者 (To littlepig with love)時間10年前發表 (2014/10/24 23:33), 10年前編輯推噓0(003)
留言3則, 3人參與, 最新討論串3/4 (看更多)
※ 引述《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]] : 第一個問題是若我想要確認某個字元是否已在這個nested list中,應該怎麼做? : 我用 'a' in ft 會error,只知道可以用 'a' in ft[i] : 所以我就先 flat(?) 這個 nested list 讓它變成: : ['a',10,'b',5,'c',11,'d',3] ← 但這樣好像很笨? : 第二個問題是怎麼改進這個function 的寫法,下面是我目前的寫法 : def add_occurrence(x, ft): : nt = [] : new_ft = [x for y in ft for x in y] : if x not in new_ft: : nt += [x,1] : ft.extend([nt]) : else: : for L in ft: : if x in L: : L[1] += 1 : return None : 看起來可能很笨,但因為我目前也只學到 list 相關的進度, : 我想請問如何改善這個function的效率? 幫 mikapauli 大大整理一下: def add_occurence(ch, ft): keys = list(zip(*ft))[0] if ch in keys: ft[keys.index(ch)][1] += 1 else: ft.append([ch,1]) return ft : 可以怎麼改進這個 function 的寫法?因為我覺得它的效率似乎不太好, : 當我用它去跑一個很大的文件檔(幾萬字的txt file),要跑上超過一分鐘。 : 我總覺得一定是我寫的function 太爛了所以才要跑這麼久 Orz... : 在此先感謝各位高手。 -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 111.243.149.233 ※ 文章網址: http://www.ptt.cc/bbs/Python/M.1414193614.A.EB8.html

10/25 08:31, , 1F
看來應該要先find,不然做了兩次搜尋
10/25 08:31, 1F
那就改成下面這樣 :) def add_occurence(ch, ft): pos = ''.join(list(zip(*ft))[0]).find(ch) if pos != -1: ft[pos][1] += 1 else: ft.append([ch,1]) return ft >>> ft = [['a',10],['b',5],['c',11],['d',3]] >>> add_occurence('a',ft) [['a', 11], ['b', 5], ['c', 11], ['d', 3]] >>> add_occurence('i',ft) [['a', 11], ['b', 5], ['c', 11], ['d', 3], ['i', 1]] 不過這樣的寫法只適用於這一題哦! ※ 編輯: bigpigbigpig (111.243.149.233), 10/25/2014 12:04:02 ※ 編輯: bigpigbigpig (111.243.149.233), 10/25/2014 12:06:16

10/25 12:41, , 2F
謝謝,以後學到一些新function時我會注意的。
10/25 12:41, 2F

10/25 12:48, , 3F
在這裏有搜尋需要其實可以先把 ft 轉成 dict 會比較好
10/25 12:48, 3F
如果可以不管 'a','b','c','d' 的順序,dict() 確實比較方便。 def add_occurence(ch, ft): D = dict(ft) D[ch] = D.get(ch, 0) + 1 return [ [ k, v ] for k, v in D.items() ] ※ 編輯: bigpigbigpig (111.243.149.233), 10/25/2014 13:28:18 ※ 編輯: bigpigbigpig (111.243.149.233), 10/25/2014 13:29:40
文章代碼(AID): #1KIk7Ewu (Python)
討論串 (同標題文章)
文章代碼(AID): #1KIk7Ewu (Python)