找出表中for项和rang中for数的区别

2024-10-05 13:47:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在用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循环。任何帮助都将不胜感激!你知道吗


Tags: of答案in程序foritem事情list
2条回答

在for循环中声明的参数item是一个新变量,它每次都保存对数组中下一个字符串的引用。你知道吗

实际上,您在循环中所做的是重新定义变量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)

此外,字符串是不可变的,因此我建议您查看以下问答:Aren't Python strings immutable? Then why does a + " " + b work?

此处:

item = whatever_happens_doesnt_matter()

item承载的引用在第一种情况下被创建并丢弃,并且与原始列表中的引用不同(变量名是重新分配的)。因为字符串是不可变的,所以没有办法让它工作。你知道吗

这就是为什么这本书必须使用非常不连贯的for .. range和索引原始列表结构,以确保分配回正确的字符串引用。可怕的。你知道吗

一个更好的、更具python风格的方法是使用列表理解重新生成列表:

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

更多列表理解方法:Appending the same string to a list of strings in Python

相关问题 更多 >

    热门问题