在Python中检查列表中是否有元素以任意前缀开头?

4 投票
4 回答
2251 浏览
提问于 2025-04-17 17:16

我想检查一组字符串 targets 中是否有哪个字符串是以一组给定的 prefixes 开头的,比如:

prefixes = ["a", "b", "c"]
targets = ["abar", "xbar"]

然后检查 targets 中的任何元素是否有一个前缀在 prefixes 中(并找出这些符合条件的 targets 元素,以及它们匹配的第一个前缀)。在这里,"abar" 是唯一符合条件的元素。我的版本是:

for t in target:
  if any(map(lambda x: t.startswith(x), prefixes)):
    print t

有没有更好、更短、更快的方法可以用普通的 Python 或 numpy 实现呢?

4 个回答

1

我在结果中使用了列表来存储前缀,因为可能会有多个匹配项。

>>> prefixes = ["a", "b", "c"]
>>> targets = ["abar", "xbar"]
>>> result = {t:[p for p in prefixes if t.startswith(p)] for t in targets}
>>> result
{'abar': ['a'], 'xbar': []}

如果你需要过滤掉空列表的话。

>>> result = {k:v for k,v in result.items() if v}
>>> result
{'abar': ['a']}
2

和@DSM说的一样

你可以使用filter这个功能

>>> prefixes = ("a", "b", "c")
>>> targets = ["abar", "xbar"]
>>> filter(lambda t: t.startswith(prefixes), targets)
['abar']
2

如果你想要所有的匹配结果,可以使用这个列表推导式:

>>> from itertools import product
>>> matches = [(t,p) for t,p in product(targets,prefixes) if t.startswith(p)]
>>> print(matches)
[('abar', 'a'), ('cbar', 'c')]

如果你只想要第一个匹配的结果,可以用next配合列表推导式,这样可以快速判断是否有匹配的结果。

>>> nextmatch = next(((t,p) for t,p in product(targets,prefixes) if t.startswith(p)), None)
>>> print(nextmatch)
[('abar', 'a')]

撰写回答