For 循环中的 Python 列表

标签 python string list loops

我是 Python 新手,对使用 for 循环更新列表有疑问。这是我的代码:

urls = ['http://www.city-data.com/city/javascript:l("Abbott");' , 'http://www.city-data.com/city/javascript:l("Abernathy");' ,

'http://www.city-data.com/city/Abilene-Texas.html' ,'http://www.city-data.com/city/javascript:l("Abram-Perezville");' ,  

'http://www.city-data.com/city/javascript:l("Ackerly");' , 'http://www.city-data.com/city/javascript:l("Adamsville");', 

'http://www.city-data.com/city/Addison-Texas.html']

for url in urls:
    if "javascript" in url:
        print url
        url = url.replace('javascript:l("','').replace('");','-Texas.html')
        print url

for url in urls:
    if "javascript" in url:
        url = url.replace('javascript:l("','').replace('");','-Texas.html')
print "\n"  
print urls

我使用了第一个 for 循环来检查语法是否正确,并且它运行良好。但是第二个for循环是我想使用的代码,但是它不能正常工作。我将如何使用第二个 for 循环全局更新列表,以便我可以在 for 循环之外打印或存储更新后的列表?

最佳答案

您可以使用索引更新列表项:

for i, url in enumerate(urls):
    if "javascript" in url:
        urls[i] = url.replace('javascript:l("','').replace('");','-Texas.html')

另一种选择是使用列表理解:

def my_replace(s):
    return s.replace('javascript:l("','').replace('");','-Texas.html')

urls[:] = [my_replace(url) if "javascript" in url else url for url in urls]

这里的 urls[:] 表示用列表理解创建的新列表替换 urls 列表中的所有项目。

您的代码不起作用的原因是您将变量 url 分配给其他东西,并且将对象的引用之一更改为指向其他东西不会影响其他引用资料。因此,您的代码等效于:

>>> lis = ['aa', 'bb', 'cc']
>>> url = lis[0]                   #create new reference to 'aa'
>>> url = lis[0].replace('a', 'd') #now assign url to a new string that was returned by `lis[0].replace`
>>> url 
'dd'
>>> lis[0]
'aa'

另请注意,str.replace 始终返回字符串的新副本,它永远不会更改原始字符串,因为字符串在 Python 中是不可变的。如果 lis[0] 是一个列表,并且您使用 .append.extend 等对其执行任何就地操作,那么也会影响原始列表。

关于For 循环中的 Python 列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21450874/

相关文章:

java - 字符串中的数字频率

php - 在PHP中将整数转换为X个字符串

python - 如何在 matplotlib 的轴外画一条线(在图形坐标中)

python - python 的 dict.items() 是否总是返回相同的顺序?

Python SUDS 错误 - SAXParseException

python - 删除嵌套列表中的列时列表分配索引超出范围

python - 有没有更好的方法从 Python 中的文件中读取元素?

python - 如何在Python中的Selenium中截取相同窗口大小的屏幕截图?

javascript - 如何在 jquery 中用多个字符串作为分隔符拆分一个字符串

Python打印列表列表中的第n个元素