看板 Python 關於我們 聯絡資訊
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://www.ptt.cc/bbs/Python/M.1398334261.A.B68.html
SocketAM2:容許我練習一下語法...純粹為了寫成單行的話可以這樣 04/24 19:30
SocketAM2:[i for i, obj in enumerate(L) if ''.join(map(str, 04/24 19:30
SocketAM2:L[i:])).startswith(''.join(map(str, subL)))] 04/24 19:31
SocketAM2:這樣簡潔一點 [i for i, obj in enumerate(L) if L[i:i+ 04/24 19:33
SocketAM2:len(subL)] == subL] 04/24 19:33
Microscft:i for i in range(len(L)) if L[x] == subL[0] and 04/24 19:48
Microscft:L[x+1] == subL[1] 04/24 19:48
Microscft:一個變數就可以了 也不需要用到enumerate 04/24 19:49
Microscft:腦殘了 請把後面的x改成i 04/24 19:50
Microscft:更好理解->i for i in range(len(L)) if L[i:i+2]==subL 04/24 20:07
ptero:感謝 04/27 15:40
ptero:這個我也有想過兩兩比,但是似乎效能比較差,暴力法XD 04/27 17:07