2010-11-10 50 views
24

在Python中,如何使用模糊匹配獲取列表中的項目位置(使用list.index)?Python:使用正則表達式獲取列表索引?

例如,如何獲得以下列表中*berry表格的所有水果的索引?

fruit_list = ['raspberry', 'apple', 'strawberry'] 
# Is it possible to do something like the following? 
berry_fruit_at_positions = fruit_list.index('*berry') 

任何人有任何想法?

+1

這不是一個正則表達式。 – delnan 2010-11-10 15:28:39

+2

正則表達式也不是模糊的。事實恰恰相反:他們非常嚴格和精確。 – 2010-11-10 16:02:29

回答

24

嘗試:

fruit_list = ['raspberry', 'apple', 'strawberry'] 
[ i for i, word in enumerate(fruit_list) if word.endswith('berry') ] 

回報:

[0, 2] 

根據您的匹配需求與不同的邏輯更換endswith

39

使用正則表達式:

import re 
fruit_list = ['raspberry', 'apple', 'strawberry'] 
berry_idx = [i for i, item in enumerate(fruit_list) if re.search('berry$', item)] 

而且沒有正則表達式:

fruit_list = ['raspberry', 'apple', 'strawberry'] 
berry_idx = [i for i, item in enumerate(fruit_list) if item.endswith('berry')] 
+0

應該選擇這個答案作爲答案。 – brittenb 2015-07-21 21:03:12

+0

我仍然覺得很奇怪,這是在python中完成這個相當常見的操作的最簡單的方法。在R中它只是grep('berry $',berry_idx)。是否沒有模塊實現更清晰的方式來搜索和獲取整數位置? – 2017-11-30 00:49:17