python - 通过子字符串检查列表中的元素

标签 python list

我有一个url列表(unicode),其中有很多重复。 例如,urls http://www.myurlnumber1.comhttp://www.myurlnumber1.com/foo+%bar%baz%qux 指向同一个地方.

所以我需要清除所有这些重复项。

我的第一个想法是检查元素的子字符串是否在列表中,如下所示:

for url in list:
    if url[:30] not in list:
        print(url)

但是,它尝试将文字 url[:30] 匹配到列表元素并显然返回所有元素,因为没有元素与 url[:30]< 完全匹配

有解决这个问题的简单方法吗?

编辑:

通常 url 中的主机和路径保持不变,但参数不同。出于我的目的,具有相同主机名和路径但不同参数的 url 仍然是相同的 url 并构成重复。

最佳答案

如果您认为任何 netloc 是相同的,您可以使用 urllib.parse 进行解析

from urllib.parse import  urlparse # python2 from urlparse import  urlparse 

u = "http://www.myurlnumber1.com/foo+%bar%baz%qux"

print(urlparse(u).netloc)

这会给你:

www.myurlnumber1.com

因此,要获得独特的 netloc,您可以执行以下操作:

unique  = {urlparse(u).netloc for u in urls}

如果您想保留 url 方案:

urls  = ["http://www.myurlnumber1.com/foo+%bar%baz%qux", "http://www.myurlnumber1.com"]

unique = {"{}://{}".format(u.scheme, u.netloc) for u in map(urlparse, urls)}
print(unique)

假设它们都有方案,而您没有针对同一 netloc 的 http 和 https,并认为它们是相同的。

如果你还想添加路径:

unique = {u.netloc, u.path) for u in map(urlparse, urls)}

文档中列出了属性表:

Attribute   Index   Value   Value if not present
scheme  0   URL scheme specifier    scheme parameter
netloc  1   Network location part   empty string
path    2   Hierarchical path   empty string
params  3   Parameters for last path element    empty string
query   4   Query component empty string
fragment    5   Fragment identifier empty string
username        User name   None
password        Password    None
hostname        Host name (lower case)  None
port        Port number as integer, if present  None

您只需要使用您认为独特的部分即可。

In [1]: from urllib.parse import  urlparse

In [2]: urls = ["http://www.url.com/foo-bar", "http://www.url.com/foo-bar?t=baz", "www.url.com/baz-qux",  "www.url.com/foo-bar?t=baz"]


In [3]: unique = {"".join((u.netloc, u.path)) for u in map(urlparse, urls)}

In [4]: 

In [4]: print(unique)
{'www.url.com/baz-qux', 'www.url.com/foo-bar'}

关于python - 通过子字符串检查列表中的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39725411/

相关文章:

python - 为回归重现 LightGBM 自定义损失函数

python - 增加列表列表的 Pythonic 方式

c# - 带字符串的选择排序

arrays - 在 vb.net 中存储和转换数据行 - 数组、列表、集合还是其他?

Python3 + Gunicon 19.9 + Django 2.0 不打印我的日志,但打印 django.request

python - 使用 python 区分 XML 和 unicode

python - 我如何使用列表理解创建这个嵌套列表?

perl - 有条件地将元素包含在列表中的最佳方法是什么?

python - 在字典中找到一个值?

python - 邮政数据库。 models.py 没有转化为数据库方案