我正试图得到一个for循环来比较2个值相应地编辑它,但它不起作用


# 1st loop iterates through user sentence list
for value in user_sentence:
# iterates through words_dict dictionary, the key is compared and the value is what replace value
for i in words_dict:  
if value == i:
value = words_dict[i]
print(user_sentence[1])

我不明白为什么嵌套的for循环不起作用,当我直接改变user_sentence[1]时它起作用,但是当我把它放在嵌套的循环中它不起作用。我做错了什么?

因为您将其分配给value变量,而不是分配给列表项。您可以使用enumerate遍历索引和user_sentence列表的值,然后如果value等于i,则修改当前索引处的值。

# 1st loop iterates through user sentence list
for idx,value in enumerate(user_sentence):
# iterates through words_dict dictionary, the key is compared and the value is what replace value
for i in words_dict:  
if value == i:
user_sentence[idx] = words_dict[i]
#break
print(user_sentence[1])

附带说明,您可以break我在上面的代码片段中注释的内部循环。它将在找到第一个匹配项后退出内循环,这样,您就不需要对所有字典项运行循环。

最新更新