Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/311.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 计算列表中的项目和范围中的数字之间的差异_Python_For Loop_Range - Fatal编程技术网

Python 计算列表中的项目和范围中的数字之间的差异

Python 计算列表中的项目和范围中的数字之间的差异,python,for-loop,range,Python,For Loop,Range,我正在用Python书做一些无聊的事情,我在第139页。我必须制作一个程序,在每行前面加一个“*”。然而,我的for循环在这里似乎不起作用 rawtextlist = [ 'list of interesting shows', 'list of nice foods', 'list of amazing sights'

我正在用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
所承载的引用在第一种情况下被创建并丢弃,与原始列表中的引用不同(变量名被重新分配)。因为字符串是不可变的,所以没有办法让它工作

这就是为什么这本书必须使用非常非音速的
。。范围
并为原始列表结构编制索引,以确保重新分配正确的字符串引用。糟透了

更好、更具python风格的方法是使用列表理解重建列表:

rawtextlist = ['*'+x for x in rawtextlist]

关于列表理解方法的更多信息,请参见此处:

您在for循环中声明的参数
item
是一个新变量,它每次都对数组中的下一个字符串进行引用

实际上,您在循环中所做的是重新定义变量
,指向一个新的字符串,这不是您想要的(您不需要更改列表中的字符串,只需创建新字符串并将其保存到at临时变量)

您可以使用提供的程序,也可以使用更新后的字符串创建新列表,如下所示:

    new_list = []
    for item in rawtextlist:
         new_list.append('*' + item)
    print(new_list)
或在一行解决方案中:

    new_list = ['*' + item for item in rawtextlist]
    print(new_list)

此外,字符串是不可变的,因此我建议您查看此问题并回答:

哦,好的,非常感谢您的建议!然而,你能重复一下你所说的“项目”被“创建并丢弃”是什么意思吗?