[英]Find a specific pattern (regular expression) in each item of list of strings (Python)
[英]How to find an index of an item in a list, searching the item with a regular expression in Python?
我有一个这样的清单:
lst = ['something', 'foo1', 'bar1', 'blabla', 'foo2']
是否可以使用正则表达式和lst.index()
获取以“foo”(foo1)开头的第一项的索引,例如:
ind = lst.index("some_regex_for_the_item_starting_with_foo") ?
我知道我可以创建一个计数器和一个 for 循环并使用方法startswith()
。 我很好奇我是否错过了一些更短更优雅的方式。
我认为没关系,如果它做你真正想要的,你可以使用startswith方法(我不确定你是否真的需要regEx - 但是可以轻松修改下面的代码以使用regEx):
data = ['text', 'foo2', 'foo1', 'sample']
indeces = (i for i,val in enumerate(data) if val.startswith('foo'))
或使用正则表达式:
from re import match
data = ['text', 'foo2', 'foo1', 'sample']
indeces = (i for i,val in enumerate(data) if match('foo', val))
没有办法使用lst.index
来做到这一点,但是这里有一种替代方法,您可能会发现它比 for 循环更优雅:
try:
ind = (i for i, v in enumerate(lst) if v.startswith("foo")).next()
except StopIteration:
ind = -1 # or however you want to say that the item wasn't found
正如 senderle 在评论中指出的那样,这可以通过使用next()
内置 function (2.6+) 来缩短,默认值将其缩短为一行:
ind = next((i for i, v in enumerate(lst) if v.startswith("foo")), -1)
不,不幸的是list.index
没有key
参数。 有一个解决方案可能是
# warning: NOT working code
result = L.index(True, key=lambda x: regexp.match(x) is not None)
此外,鉴于我刚刚发现lambda
显然在 python 社区中被认为是可憎的,我不确定将来是否会添加更多key
参数。
内置这样的东西会很酷。Python 没有。 使用 itertools 有一些有趣的解决方案。 (这些也让我希望有一个itertools.takewhile_false
。如果它存在,这些将更具可读性。)
>>> from itertools import takewhile
>>> import re
>>> m = re.compile('foo.*')
>>> print len(tuple(itertools.takewhile(lambda x: not m.match(x), lst)))
1
这是我的第一个想法,但它需要你创建一个临时元组并获取它的长度。 然后我想到你可以做一个简单的求和,并避免临时列表:
>>> print sum(1 for _ in takewhile(lambda x: not m.match(x), lst))
1
但这也有点麻烦。 我更喜欢尽可能避免丢弃的变量。 让我们再试一次。
>>> sum(takewhile(bool, (not m.match(x) for x in lst)))
1
好多了。
l = ['something', 'foo1', 'bar1', 'blabla', 'foo2']
l.index(filter(lambda x:x.startswith('foo'),l)[0])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.