有关在 数字 列表中检索部分匹配项的方法,请访问:
但是,如果您正在寻找如何检索 字符串 列表的部分匹配项,您会在下面的答案中找到简要说明的最佳方法。
SO: Python list lookup with partial match shows how to return a bool
, if a list
contains an element that partially matches (eg begins
, ends
或 contains
) 某个字符串。但是你怎么能 _返回元素本身_,而不是 True
或 False
例子:
l = ['ones', 'twos', 'threes']
wanted = 'three'
在这里,链接问题中的方法将返回 True
使用:
any(s.startswith(wanted) for s in l)
那么如何返回元素 'threes'
呢?
原文由 vestland 发布,翻译遵循 CC BY-SA 4.0 许可协议
startswith
和in
,返回一个布尔值。in
运算符是对成员资格的测试。list-comprehension
或filter
来执行。list-comprehension
和in
是经过测试的最快的实现。l = list(map(str.lower, l))
。filter
:filter
creates afilter
object, solist()
is used to show all the matching values in alist
.list-comprehension
哪个实施更快?
words
来自nltk v3.7
--- 的语料库在 Jupyter 实验室进行测试,它有 236736 个单词'three'
的词['three', 'threefold', 'threefolded', 'threefoldedness', 'threefoldly', 'threefoldness', 'threeling', 'threeness', 'threepence', 'threepenny', 'threepennyworth', 'threescore', 'threesome']
%timeit
结果