繁体   English   中英

从字符串列表中删除重复项和子字符串

[英]Remove duplicates and substrings from a list of strings

假设我有一个列表:

a = [
    'www.google.com',
    'google.com',
    'tvi.pt',
    'ubs.ch',
    'google.it',
    'www.google.com'
]

我想删除重复项和子字符串以保留如下列表:

b = [
    'www.google.com',
    'tvi.pt',
    'ubs.ch',
    'google.it'
]

你知道一个有效的方法吗?

目标是保留更长的字符串,这就是为什么www.google.com优于google.com的原因。

可以编辑此解决方案以更好地满足您的需求。 编辑函数get_domain以更好地选择分组条件*和choose_item function 以更好地选择组中的最佳项目。

from itertools import groupby

a = ['www.google.com', 'google.com', 'tvi.pt', 'ubs.ch', 'google.it', 'www.google.com']

def get_domain(url):
    # Example: 'www.google.com' -> 'google.com'
    return '.'.join(url.split('.')[-2:])

def choose_item(iterable):
    # Ex. input: ['www.google.com', 'google.com',  'www.google.com']
    # Ex. output: 'www.google.com' (longest string)
    return sorted(iterable, key=lambda x: -len(x))[0]

results = []
for domain,grp in groupby(sorted(a, key=get_domain), key=get_domain):
    results.append(choose_item(grp))

print(results)

Output:

['www.google.com', 'google.it', 'tvi.pt', 'ubs.ch']

*另一个答案建议使用 tld 库。

如果您正在寻找的是唯一一级域的列表,给定一个任意的 URL 列表,请查看tld模块。 它会让你的事情变得更容易。

根据文档,这里有一个片段,您可以根据自己的需要进行调整:

from tld import get_fld

urls = [
    'www.google.com',
    'google.com',
    'tvi.pt',
    'ubs.ch',
    'google.it',
    'www.google.com'
]

unique_domains =  list({
    get_fld(url, fix_protocol=True) for url in urls
}) 

上面的代码将unique_domains设置为:

['ubs.ch', 'google.it', 'tvi.pt', 'google.com']

您可以按如下方式删除重复项:

f = list(dict.fromkeys(a))

这将过滤掉重复的“www.google.com”,但不会过滤掉子字符串。 正如 Caveman 船长在他的评论中所写,这需要更多的澄清。

def remove_duplicates_and_substrings(input):
output = []
for i in input:
    if i not in output:
        if not any(i in s for s in output):
            output.append(i)
return output

它可能不是最好的方法,但它确实可以按照您的意愿进行操作。 它首先检查输入列表中的字符串是否不在 output 列表中。 然后它检查它的任何部分是否已经在 output 字符串之一中。 如果不是这种情况,它将把它添加到 output 列表中。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM