gpt4 book ai didi

python - 如何使用反向引用作为索引来通过列表替换?

转载 作者:行者123 更新时间:2023-12-01 00:47:35 25 4
gpt4 key购买 nike

我有一个 list

fruits = ['apple', 'banana', 'cherry']

我喜欢用列表中的索引替换所有这些元素。我知道,我可以浏览列表并使用字符串替换,例如

text = "I like to eat apple, but banana are fine too."
for i, fruit in enumerate(fruits):
text = text.replace(fruit, str(i))

使用正则表达式怎么样?使用 \number 我们可以反向引用匹配项。但是

import re

text = "I like to eat apple, but banana are fine too."
text = re.sub('apple|banana|cherry', fruits.index('\1'), text)

不起作用。我收到错误消息 \x01 不在水果中。但 \1 应该引用 'apple'

我对最有效的替换方法感兴趣,但我也喜欢更好地理解正则表达式。如何从正则表达式中的反向引用获取匹配字符串。

非常感谢。

最佳答案

使用正则表达式。

例如:

import re

text = "I like to eat apple, but banana are fine too."
fruits = ['apple', 'banana', 'cherry']

pattern = re.compile("|".join(fruits))
text = pattern.sub(lambda x: str(fruits.index(x.group())), text)
print(text)

输出:

I like to eat 0, but 1 are fine too.

关于python - 如何使用反向引用作为索引来通过列表替换?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56836521/

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