为什么这个函数不能从列表中移除项目?

2024-04-24 05:57:15 发布

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

我在一个.py文件中有一个函数,用于获取链接列表(url字符串)和链接的私有路径列表,并将其从列表中删除,然后返回一个新列表。你知道吗

例如,从包含字符串“/files”的列表中删除任何项。你知道吗

以下是列表:

private_paths = ['/sites/', '/files']
url_strings = ['http://example.com/files/image1.jpg', 'http://example.com/index.html', 'http://example.com/about.html', 'http://example.com/sites/js/example.js']

等等。。等。。你知道吗

功能如下:

def rmvPrivate(privatepaths, links):

copy = list(links)

for link in copy:
    for path in privatepaths:
        if path in link:
            # printed link and path here
            copy.remove(link) 
return copy

呼叫方式:

rmvPrivate(private_paths, url_strings)

函数正在查找和匹配url\u strings列表中的链接,这些链接包含private\u paths列表中的私有路径,但它们没有被删除?你知道吗

提前谢谢你给我的任何建议!你知道吗

上下文: 我正在尝试编写一个脚本,该脚本进入网站的主页,获取所有链接并将它们添加到一个数组中,然后这个数组将用于python/selenium测试。。你知道吗

再次感谢!你知道吗


Tags: path函数incomhttpurl列表链接
1条回答
网友
1楼 · 发布于 2024-04-24 05:57:15

你复制了一份名单。如果你从副本中删除,那么原件就永远不会改变。你知道吗

做这个

private_paths = ['/sites/', '/files/']
url_strings = ['http://example.com/files/image1.jpg', 'http://example.com/index.html', 'http://example.com/about.html', 'http://example.com/sites/js/example.js']

def rmvPrivate(privatepaths, links):
    for link in links:
        for path in privatepaths:
            if path in link:
                # printed link and path here
                links.remove(link) 



rmvPrivate(private_paths, url_strings)

print url_strings

请注意,如果就地更改列表,则返回值(从未捕获)是多余的。你知道吗

或者,您可以使用原始代码捕获函数的返回值。你知道吗

public_url_strings = rmvPrivate(private_paths, url_strings)

以Alex Martellis在链接的dupe问题中的答案为基础。你知道吗

def rmvPrivate(privatepaths, links):
    links[:] = [link for link in links if all(pp not in link for pp in private_paths)]

相关问题 更多 >