首页 > 解决方案 > 我正在尝试获取一个 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]直接更改时它起作用,但是当我将它放入嵌套循环时它不起作用。我究竟做错了什么?

标签: pythonfor-loopnested-for-loop

解决方案


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

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


推荐阅读