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

看板Python作者 (海洋)時間10年前發表 (2014/10/24 15:49), 10年前編輯推噓0(0010)
留言10則, 2人參與, 最新討論串1/4 (看更多)
大家好 我目前正在自學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的效率? 可以怎麼改進這個 function 的寫法?因為我覺得它的效率似乎不太好, 當我用它去跑一個很大的文件檔(幾萬字的txt file),要跑上超過一分鐘。 我總覺得一定是我寫的function 太爛了所以才要跑這麼久 Orz... 在此先感謝各位高手。 -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 149.159.27.253 ※ 文章網址: http://www.ptt.cc/bbs/Python/M.1414165778.A.413.html ※ 編輯: hohiyan (149.159.27.253), 10/25/2014 00:04:46

10/25 00:30, , 1F
第一個問題,可以用'a' in list(zip(*ft))[0]
10/25 00:30, 1F

10/25 00:46, , 2F
第二個問題,就你的寫法:
10/25 00:46, 2F

10/25 00:46, , 3F
nt = []; nt += [x, 1]; ft.extend([nt])
10/25 00:46, 3F

10/25 00:46, , 4F
可以直接寫ft.append([x, 1])
10/25 00:46, 4F

10/25 00:46, , 5F
if x in L 可以寫 if x == L[0]
10/25 00:46, 5F

10/25 00:52, , 6F
結合第一個問題定義new_ft = list(zip(*ft))[0]的話
10/25 00:52, 6F

10/25 00:52, , 7F
第二個問題else區塊內可以寫成
10/25 00:52, 7F

10/25 00:53, , 8F
ft[new_ft.index(x)][1] += 1
10/25 00:53, 8F

10/25 00:57, , 9F
另外你可以參考一下dict
10/25 00:57, 9F

10/25 12:38, , 10F
感謝!有很多地方自己想好久都想不到,謝謝提醒。
10/25 12:38, 10F
文章代碼(AID): #1KIdKIGJ (Python)
討論串 (同標題文章)
文章代碼(AID): #1KIdKIGJ (Python)