今天我遇到了以下结构:
import re
l = list('1234')
print(re.sub('.', lambda _: l.pop(0), 'abcd'))
基本上,它使用 sub 和具有副作用的 repl 函数。
撇开有争议的文体问题不谈,这是否定义明确?
例如,我在文档中找不到任何地方可以保证 repl 会以任何特定的顺序 在匹配项上调用(也确实 恰好一次,尽管官方措辞在某种程度上可以解释)。此代码是否存在任何其他实际或潜在问题?
请您参考如下方法:
根据documentation的 re.sub :
Return the string obtained by replacing the leftmost non-overlapping occurrences of
patterninstringby the replacementrepl.
和:
If
replis a function, it is called for every non-overlapping occurrence of pattern.
因此很明显 re.sub从左到右搜索并替换给定 pattern 的每个匹配项与 repl 的返回值功能。所以是的,您的代码的行为定义明确。但是,它效率不高,因为您是迭代地弹出列表的第一项,每次迭代的时间复杂度为 O(n)。您可以改用迭代器在 O(1) 时间内实现相同的副作用:
import re
i = iter('1234')
print(re.sub('.', lambda _: next(i), 'abcd'))
这也输出:
1234
