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

看板Python作者 (企鵝)時間9年前 (2014/10/25 00:56), 編輯推噓0(001)
留言1則, 1人參與, 最新討論串2/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] ← 但這樣好像很笨? 樸實的作法可以一個一個看 in_list = False for s in ft: if s[0] == 'a': in_list = True break : 第二個問題是怎麼改進這個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 相關的進度, 樸實的作法也可以一個一個看 def add_occurrence(x, ft): for s in ft: if s[0] == x: s[1] += 1 return ft.append([x, 1]) : 我想請問如何改善這個function的效率? : 可以怎麼改進這個 function 的寫法?因為我覺得它的效率似乎不太好, : 當我用它去跑一個很大的文件檔(幾萬字的txt file),要跑上超過一分鐘。 : 我總覺得一定是我寫的function 太爛了所以才要跑這麼久 Orz... : 在此先感謝各位高手。 你想做的事情可能用 dict 比較適合 之後學到的時候可以注意一下 -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 111.243.103.58 ※ 文章網址: http://www.ptt.cc/bbs/Python/M.1414169761.A.177.html

10/25 12:40, , 1F
謝謝penguin7272,我會好好參考你的意見。
10/25 12:40, 1F
文章代碼(AID): #1KIeIX5t (Python)
文章代碼(AID): #1KIeIX5t (Python)