說,我們有一個多層迭代的一些字符串在「最後」的水平,是字符串是可迭代的,但我覺得你得到了我的意思:grep的多層迭代相匹配的字符串(Python)的
['something',
('Diff',
('diff', 'udiff'),
('*.diff', '*.patch'),
('text/x-diff', 'text/x-patch')),
('Delphi',
('delphi', 'pas', 'pascal', 'objectpascal'),
('*.pas',),
('text/x-pascal',['lets', 'put one here'],)),
('JavaScript+Mako',
('js+mako', 'javascript+mako'),
('application/x-javascript+mako',
'text/x-javascript+mako',
'text/javascript+mako')),
...
]
是否有任何方便的方法,我可以實現一個搜索,會給我的匹配字符串的索引?我想東西會起到這樣的事情(在上面的列表data
):
>>> grep('javascript', data)
,它會返回[(2,1,1),(2,2,0),(2, 2,1),(2,2,2)]也許。也許我錯過了一種類似的解決方案,它不會返回任何結果,但可以幫助我找到一些字符串迭代器的迭代列表中的一些字符串。
我寫了一點點,但它似乎少年和不雅的,所以我想我會問這裏。我想我可以繼續嵌套異常,就像我在這裏開始的那樣,將函數支持的層次數嵌套起來,但我希望得到一些整潔,抽象,pythonic的東西。
import re
def rgrep(s, data):
''' given a iterable of strings or an iterable of iterables of strings,
returns the index/indices of strings that contain the search string.
Args::
s - the string that you are searching for
data - the iterable of strings or iterable of iterables of strings
'''
results = []
expr = re.compile(s)
for item in data:
try:
match = expr.search(item)
if match != None:
results.append(data.index(item))
except TypeError:
for t in item:
try:
m = expr.search(t)
if m != None:
results.append((list.index(item), item.index(t)))
except TypeError:
''' you can only go 2 deep! '''
pass
return results
這將有助於你展示你到目前爲止的內容,以及你自己的解決方案的哪一部分給你帶來麻煩。 – 2009-10-18 13:15:47