我正在尝试获取一个 for 循环来比较 2 个值,相应地对其进行编辑,但它不起作用

I am trying to get a for loop to compare 2 values edit it accordingly, but it is not working

# 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 我在上面的代码片段中评论的内部循环。它会在找到第一个匹配项后退出内部循环,这样,您不需要 运行 循环所有字典项。