作者ptero (ptero)
看板Python
標題[問題] 找出sublist在list中出現過的位置
時間Thu Apr 24 18:10:58 2014
ex: L = [1, 3, 4, 1, 2, 5, 6, 1, 2, 7, 4, 8, 1, 1, 2]
subL = [1, 2]
我想要找出[1,2]在L出現的位置,像是這題分別是L[3:4], L[7:8], L[13:14]
請問python有比較方便的搜尋方式嗎?
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 140.121.199.229
※ 文章網址: http://webptt.com/m.aspx?n=bbs/Python/M.1398334261.A.B68.html
1F:→ SocketAM2:容許我練習一下語法...純粹為了寫成單行的話可以這樣 04/24 19:30
2F:→ SocketAM2:[i for i, obj in enumerate(L) if ''.join(map(str, 04/24 19:30
3F:→ SocketAM2:L[i:])).startswith(''.join(map(str, subL)))] 04/24 19:31
4F:→ SocketAM2:這樣簡潔一點 [i for i, obj in enumerate(L) if L[i:i+ 04/24 19:33
5F:→ SocketAM2:len(subL)] == subL] 04/24 19:33
6F:推 Microscft:i for i in range(len(L)) if L[x] == subL[0] and 04/24 19:48
7F:→ Microscft:L[x+1] == subL[1] 04/24 19:48
8F:→ Microscft:一個變數就可以了 也不需要用到enumerate 04/24 19:49
9F:→ Microscft:腦殘了 請把後面的x改成i 04/24 19:50
10F:→ Microscft:更好理解->i for i in range(len(L)) if L[i:i+2]==subL 04/24 20:07
11F:→ ptero:感謝 04/27 15:40
12F:→ ptero:這個我也有想過兩兩比,但是似乎效能比較差,暴力法XD 04/27 17:07