2024-04-19 17:22:20 发布
网友
今天我遇到了以下结构:
import re l = list('1234') print(re.sub('.', lambda _: l.pop(0), 'abcd'))
基本上,它使用带有副作用的sub函数。你知道吗
sub
抛开有争议的文体问题不谈,这一点定义得好吗?
例如,我在文档中找不到任何地方可以保证repl会以任何特定的顺序调用匹配项(当然也不能只调用一次,尽管官方的措辞有点开放性)。此代码是否存在任何其他实际或潜在的问题?你知道吗
repl
根据re.sub的documentation:
re.sub
Return the string obtained by replacing the leftmost non-overlapping occurrences of pattern in string by the replacement repl.
pattern
string
以及:
If repl is a function, it is called for every non-overlapping occurrence of pattern.
因此很明显,re.sub从左到右搜索,并用repl函数的返回值替换给定pattern的每个出现。所以是的,代码的行为定义得很好。但是,这是没有效率的,因为您正在迭代地弹出列表的第一项,这需要每次迭代的时间复杂度O(n)。相反,您可以使用迭代器在O(1)时间内实现相同的副作用:
import re i = iter('1234') print(re.sub('.', lambda _: next(i), 'abcd'))
这还输出:
1234
根据
re.sub
的documentation:以及:
因此很明显,
re.sub
从左到右搜索,并用repl
函数的返回值替换给定pattern
的每个出现。所以是的,代码的行为定义得很好。但是,这是没有效率的,因为您正在迭代地弹出列表的第一项,这需要每次迭代的时间复杂度O(n)。相反,您可以使用迭代器在O(1)时间内实现相同的副作用:这还输出:
相关问题 更多 >
编程相关推荐