[问题] 搜寻 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