说,我们有一个多层迭代的一些字符串在“最后”的水平,是字符串是可迭代的,但我觉得你得到了我的意思: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