我正在用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循环。任何帮助都将不胜感激!你知道吗
在for循环中声明的参数
item
是一个新变量,它每次都保存对数组中下一个字符串的引用。你知道吗实际上,您在循环中所做的是重新定义变量
item
以指向一个新的字符串,这不是您想要的(您不需要更改列表中的字符串,只需要创建新字符串并将其保存到at临时变量)。你知道吗您可以使用提供的程序,也可以使用更新的字符串创建新的列表,如下所示:
或在单行解决方案中:
此外,字符串是不可变的,因此我建议您查看以下问答:Aren't Python strings immutable? Then why does a + " " + b work?
此处:
item
承载的引用在第一种情况下被创建并丢弃,并且与原始列表中的引用不同(变量名是重新分配的)。因为字符串是不可变的,所以没有办法让它工作。你知道吗这就是为什么这本书必须使用非常不连贯的
for .. range
和索引原始列表结构,以确保分配回正确的字符串引用。可怕的。你知道吗一个更好的、更具python风格的方法是使用列表理解重新生成列表:
更多列表理解方法:Appending the same string to a list of strings in Python
相关问题 更多 >
编程相关推荐