【问题标题】:The string 'in' operator in CPythonPython中的字符串'in'运算符
【发布时间】:2020-10-11 16:28:39
【问题描述】:

据我了解,当我在 Python 中执行 'foo' in 'abcfoo' 时,解释器会尝试在后台调用 'abcfoo'.__contains__('foo')

这是一个接受多种算法的string matching(又称搜索)操作,例如:

我如何知道给定实现可能使用哪种算法? (例如,带有CPython 的 Python 3.8)。我无法查看这些信息,例如the source code 用于字符串的 CPython。我不熟悉它的代码库,例如我找不到为它定义的__contains__

【问题讨论】:

  • 实现细节可能对您的程序无关紧要。如果他们这样做了,那么您可能会遇到设计问题,并且可能想要自己编写扩展或实现算法,可能使用不同的语言或使用库。如果您只是好奇,请查看this thread
  • 您查看的文件有误 - 请参阅 here
  • @ggorlen 我很欣赏你的评论,但恭敬地不同意。方法的运行时间可能是一个重要的考虑因素。我不认为这是一个方法的用户应该忽略的实现细节。
  • @AmelioVazquez-Reina:请注意,如果您的字符串很大,那么进行调查可能是有意义的,否则如果您关心原始处理速度,那么 Python 可能不是最好考虑的语言。谁选择 Python 并不是因为它的速度。

标签: python python-3.x string algorithm cpython


【解决方案1】:

根据source code

/* fast search/count implementation, based on a mix between boyer-
   moore and horspool, with a few more bells and whistles on the top.
   for some more background, see: http://effbot.org/zone/stringlib.htm */

该链接表明它已在 find, index, split, replace, __contains__ 中使用,尽管它现在可能已经过时了。

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-03-25
  • 2012-07-11
  • 2015-07-25
  • 1970-01-01
  • 2013-08-10
相关资源
最近更新 更多