作者CaptPlanet (ep)
看板Python
標題[問題] 請問有什麼辦法加快這個 for loop 嗎?
時間Tue Feb 27 15:53:13 2018
有list_a, list_b兩個list
list_a 有大約 70000 個 elements
list_b 大約 3 million 個 elements
程式大致如下:
res_li = []
for x in list_b:
try:
res_li.append(list_a.index(x))
except:
res_li.append("")
對 list_b 中的每一個 element
在 list_a 中找到一樣 element 把他的 index 加到新的 list 中
隨著 iteration 增加 速度變得越來越慢,
想請教各位為何會有這個現象以及有什麼方法加速這個 for loop 呢?
謝謝各位高手
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 110.28.65.74
※ 文章網址: https://webptt.com/m.aspx?n=bbs/Python/M.1519717995.A.701.html
1F:→ uranusjr: 簡單的方法是把 list_a 的 index 用 dict cache 起來 02/27 16:03
2F:→ uranusjr: 每個 b 裡的值都要在 a 從頭找一次當然會慢 02/27 16:03
3F:→ CaptPlanet: 感恩 已解決 02/27 16:21
4F:推 Yshuan: 做一個 dict([(v, i) for i, v in enumerate(list_a)]) 02/27 16:51
5F:→ Yshuan: 用空間換取時間這樣... 02/27 16:51
6F:推 Yshuan: res_li = map(lambda k: new_dict.get(k, ""), list_b) 02/27 16:54
7F:推 thefomalhaut: cython or numpy? 02/28 00:53
8F:→ secondsee: 或可用set找出交集, 直接拿去list_a比對 02/28 10:36
9F:→ secondsee: check = set(list_a) & set(list_b) 02/28 10:41
10F:→ secondsee: res_li = [i for i,x in enumerate(a) if x in check] 02/28 10:43
11F:推 vfgce: 樓上的解法有誤...也沒有比dict快. 02/28 11:58
12F:推 vfgce: Y大解法ok,只是map回傳的是iterator,再轉成list似乎沒有 02/28 12:03
13F:→ vfgce: 比直接用list comprehension快. 02/28 12:04
14F:推 eggeggss: 2個list轉set後intersection再產生新的list 10/27 16:42