python - 找出 for item in list 和 for number in range 之间的区别
问题描述
我正在用 Python 书自动化无聊的东西,在第 139 页。我必须编写一个程序在每行前面添加一个“*”。但是,我的 for 循环似乎在这里不起作用。
rawtextlist = [
'list of interesting shows',
'list of nice foods',
'list of amazing sights'
]
for item in rawtextlist:
item = '*' + item
我的输出如下。使用上面的代码时,我错过了每行前面的“*”字符。
list of interesting shows
list of nice foods
list of amazing sights
书中给出的答案是这样的。
for i in range(len(rawtextlist)):
rawtextlist[i] = '*' + rawtextlist[i]
该程序仅适用于书中提供的答案,不适用于我的 for 循环。任何帮助将不胜感激!
解决方案
这里:
item = whatever_happens_doesnt_matter()
承载的引用item
在第一种情况下被创建并丢弃,并且与原始列表中的引用不同(变量名被重新分配)。而且没有办法让它工作,因为字符串无论如何都是不可变的。
这就是为什么本书必须使用非常unpythonicfor .. range
并索引原始列表结构以确保分配回正确的字符串引用。糟糕的。
更好和更 Pythonic 的方法是使用列表理解重建列表:
rawtextlist = ['*'+x for x in rawtextlist]
更多关于列表理解方法的信息:Appending the same string to a list of strings in Python
推荐阅读
- javascript - Angular 订阅无法按我的预期工作
- php - 使用 Composer 安装包
- node.js - 测试快速 HTTPS 服务器时的“app.address 不是函数”
- django-rest-framework - 如何在 django restframework 中获取项目名称而不是项目 ID(外键案例)
- dart - 使用带有 add() 方法的 dart 将元素添加到 2d 列表
- flutter - Flutter:我可以使用 Provider.of
在普通类组件中? - kotlin - 如何在 Kotlin 中制作集合的深拷贝?
- sql-server - SSAS 标准版表格模型过程 - 内存不足错误
- node.js - 如何使用正确的导入语法来替换“require”?
- meshlab - Meshlab 加权简化