首页 > 解决方案 > 找出 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 循环。任何帮助将不胜感激!

标签: pythonfor-looprange

解决方案


这里:

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


推荐阅读