如何从字符串列表中检索部分匹配项

新手上路,请多包涵

有关在 数字 列表中检索部分匹配项的方法,请访问:


但是,如果您正在寻找如何检索 字符串 列表的部分匹配项,您会在下面的答案中找到简要说明的最佳方法。

SO: Python list lookup with partial match shows how to return a bool , if a list contains an element that partially matches (eg begins , endscontains ) 某个字符串。但是你怎么能 _返回元素本身_,而不是 TrueFalse

例子:

 l = ['ones', 'twos', 'threes']
wanted = 'three'

在这里,链接问题中的方法将返回 True 使用:

 any(s.startswith(wanted) for s in l)

那么如何返回元素 'threes' 呢?

原文由 vestland 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.5k
2 个回答
  • startswithin ,返回一个布尔值。
  • in 运算符是对成员资格的测试。
  • 这可以通过 list-comprehensionfilter 来执行。
  • 使用 list-comprehensionin 是经过测试的最快的实现。
  • 如果大小写不是问题,请考虑将所有单词映射为小写。
    • l = list(map(str.lower, l))
  • 使用 python 3.11.0 测试

filter

  • Using filter creates a filter object, so list() is used to show all the matching values in a list .
 l = ['ones', 'twos', 'threes']
wanted = 'three'

# using startswith
result = list(filter(lambda x: x.startswith(wanted), l))

# using in
result = list(filter(lambda x: wanted in x, l))

print(result)
[out]:
['threes']

list-comprehension

 l = ['ones', 'twos', 'threes']
wanted = 'three'

# using startswith
result = [v for v in l if v.startswith(wanted)]

# using in
result = [v for v in l if wanted in v]

print(result)
[out]:
['threes']

哪个实施更快?

  • 使用 words 来自 nltk v3.7 --- 的语料库在 Jupyter 实验室进行测试,它有 236736 个单词
  • 带有 'three' 的词
    • ['three', 'threefold', 'threefolded', 'threefoldedness', 'threefoldly', 'threefoldness', 'threeling', 'threeness', 'threepence', 'threepenny', 'threepennyworth', 'threescore', 'threesome']
 from nltk.corpus import words

%timeit list(filter(lambda x: x.startswith(wanted), words.words()))
%timeit list(filter(lambda x: wanted in x, words.words()))
%timeit [v for v in words.words() if v.startswith(wanted)]
%timeit [v for v in words.words() if wanted in v]

%timeit 结果

62.8 ms ± 816 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)
53.8 ms ± 982 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)
56.9 ms ± 1.33 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
47.5 ms ± 1.04 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

原文由 Trenton McKinney 发布,翻译遵循 CC BY-SA 4.0 许可协议

一个简单直接的答案:

 test_list = ['one', 'two','threefour']
r = [s for s in test_list if s.startswith('three')]
print(r[0] if r else 'nomatch')

结果:

 threefour

不确定在不匹配的情况下你想做什么。 r[0] 正是你要求的,如果有匹配,但如果没有匹配,它是未定义的。 print 处理这个问题,但您可能希望以不同的方式进行处理。

原文由 CryptoFool 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题