python - 我正在尝试获取一个 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
变量,而不是列表项。您可以使用 遍历索引和user_sentence
列表的值,然后在等于enumerate
时修改当前索引处的值。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
使用我在上面的代码片段中评论过的内部循环。它会在找到第一个匹配项后退出内部循环,这样,您不需要为所有字典项运行循环。
推荐阅读
- python - 如果语句没有执行它应该执行的操作
- python - 如何使用 Python 和 Beautiful Soup 从 HTML div 元素访问 href 值?
- jenkins - 从其他应用程序访问 jenkins 构建工件
- c++ - C ++ libcurl返回null?
- c - C语言中的时间转换
- docker-compose - 如何使用引导模式的撰写文件在 Docker 中运行 mysql 路由器
- html - 为什么没有缓存的元标记在网站中不起作用,而 HTML 页面从缓存中加载?
- javascript - 具有动态属性的Vue3重定向
- spring-boot - 如何使用 spring-boot:build-image 嵌入 CA 证书?
- apache-kafka - 如何在 kafka sink 连接器中设置特定表?