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

作者: hohiyan (海洋)   2014-10-24 23:49:34
大家好
我目前正在自學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...
在此先感謝各位高手。
作者: mikapauli (桜花)   2014-10-25 00:30:00
第一個問題,可以用'a' in list(zip(*ft))[0]第二個問題,就你的寫法:nt = []; nt += [x, 1]; ft.extend([nt])可以直接寫ft.append([x, 1])if x in L 可以寫 if x == L[0]結合第一個問題定義new_ft = list(zip(*ft))[0]的話第二個問題else區塊內可以寫成ft[new_ft.index(x)][1] += 1另外你可以參考一下dict
作者: hohiyan (海洋)   2014-10-25 12:38:00
感謝!有很多地方自己想好久都想不到,謝謝提醒。

Links booklink

Contact Us: admin [ a t ] ucptt.com