且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

For循环中的Python列表

更新时间:2022-06-18 05:30:08

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

You can update the list items using their index:

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

另一种替代方法是使用列表理解:

Another alternative is to use a list comprehension:

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列表中的所有项目替换为由列表理解创建的新列表.

Here urls[:] means replace all the items of urls list with the new list created by the list comprehension.

代码无法正常工作的原因是您将变量url分配给其他对象,并且将对象的引用之一更改为指向其他对象不会影响其他引用.因此,您的代码等效于:

The reason why your code didn't worked is that you're assigning the variable url to something else, and changing one of the reference of an object to point to something else doesn't affect the other references. So, your code is equivalent to:

>>> 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等对其执行了任何就地操作,那么这也将影响原始列表.

Also note that str.replace always returns a new copy of string, it never changes the original string because strings are immutable in Python. In case lis[0] was a list and you performed any in-place operation on it using .append, .extend etc, then that would have affected the original list as well.