2013-05-17 84 views
2

再次認識到這與SO上的一些其他問題類似,但我無法爲我的目的轉換。例如。下面Python索引正則表達式匹配的列表

import re 
a = ['rhubarb','plain custard','jam','vanilla custard','pie','cheesecake'] 
s = re.compile('custard') 

的片段,我想能夠得到一個列表

[2,4]

這是兩個custard字符串的索引。我認爲下面的問題會有所幫助,但我還沒有弄清楚如何在這裏應用它。

Python equivalent of which() in R

+4

你確定*你想'[2,4]'還是你想'[1,3]'? python中的索引從0開始。因此,如果您想要使用這些值來索引到原始列表中,它們將是錯誤的。 –

+0

嗨@JonathonReinhart [1,3]是對的。我的錯誤謝謝 –

回答

9
>>> import re 
>>> a = ['rhubarb','plain custard','jam','vanilla custard','pie','cheesecake'] 
>>> [i for i, s in enumerate(a, start=1) if re.search('custard', s)] 
[2, 4] 

Python使用0指數,所以我說的start=1參數enumerate。在實踐中,您應該離開start=1以使其默認爲start=0

+1

哇,我不知道那個額外的參數。 +1 – TerryA

+0

+1 Bam! (沒有別的需要說) –

+0

這真棒。謝謝@jamylak –