gpt4 book ai didi

python - re.sub() 具有具有副作用的替换功能

转载 作者:太空宇宙 更新时间:2023-11-04 04:02:55 25 4
gpt4 key购买 nike

今天我遇到了以下结构:

import re
l = list('1234')
print(re.sub('.', lambda _: l.pop(0), 'abcd'))

基本上,它使用 sub 和具有副作用的 repl 函数。

撇开有争议的文体问题不谈,这是否定义明确?

例如,我在文档中找不到任何地方可以保证 repl 会以任何特定的顺序 在匹配项上调用(也确实 恰好一次,尽管官方措辞在某种程度上可以解释)。此代码是否存在任何其他实际或潜在问题?

最佳答案

根据documentationre.sub :

Return the string obtained by replacing the leftmost non-overlapping occurrences of pattern in string by the replacement repl.

和:

If repl is 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

关于python - re.sub() 具有具有副作用的替换功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57875879/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com