gpt4 book ai didi

python - 从字典中替换列表中的字符串

转载 作者:行者123 更新时间:2023-12-02 04:13:16 25 4
gpt4 key购买 nike

我的代码有一些问题:

word_list = { "hello" : "1", "bye" : "2"}

sentence= ['hello you, hows things', 'hello, good thanks']

for key, value in word_list.iteritems():
for i in sentence:
i = i.replace(key, value)
print i

预期输出 = '1 你,最近怎么样''1,谢谢'

它目前不替换任何出现的hello。我想知道我的句子循环是否正确?在此之后打印 i 将准确打印出 sentence 中的内容。

最佳答案

我猜word_list(尝试将变量重命名为word_dict,我认为这样更合适)有很多项目,

for index, data in enumerate(sentence):
for key, value in word_list.iteritems():
if key in data:
sentence[index]=data.replace(key, word_list[key])

来自 ipython 的工作示例

In [1]: word_list = { "hello" : "1", "bye" : "2"}

In [2]: sentence = ['hello you, hows things', 'hello, good thanks']

In [3]: for index, data in enumerate(sentence):
...: for key, value in word_list.iteritems():
...: if key in data:
...: sentence[index]=data.replace(key, word_list[key])
...:

In [4]: sentence
Out[4]: ['1 you, hows things', '1, good thanks']

关于python - 从字典中替换列表中的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35314373/

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