按相同键排序和分组一次

Sort and group by same key once

我想按 TLDs

对带有 url 的列表进行分组

我的代码如下所示:

from itertools import groupby
from tldextract import extract

urls = sorted(urls, key=lambda x: extract(x).suffix)
grouped_urls = groupby(urls, key=lambda x: extract(x).suffix)

问题是我调用方法extract 2*n 次(where n == len(urls)),前n 次是在排序时,第二次是在分组时调用了n 次。 有没有可能做n次?

如果先将后缀添加为元组,则无需重新计算即可进行排序和分组,如下所示:

from itertools import groupby
from tldextract import extract

urls = ["www.example.com", "www.mytest.org", "www.test.com", "www.abc.com"]
urls = [(extract(url).suffix, url) for url in urls]

for k, g in groupby(sorted(urls), key=lambda x: x[0]):
    print k, list(g)

在这个例子中你会得到:

com [('com', 'www.abc.com'), ('com', 'www.example.com'), ('com', 'www.test.com')]
org [('org', 'www.mytest.org')]

根据您的 url 列表的大小,如果您一次构建所有提取的足够的列表,然后在索引列表上使用索引 排序:

from itertools import groupby, count
from tldextract import extract

c1, c2 = count(), count()

lst = [extract(x).suffix for x in urls]
urls = sorted(urls, key=lambda _: lst[next(c1)])
grouped_urls = groupby(urls, key=lambda _: lst[next(c2)])

这样做的缺点是您将进行 O(1) 索引 2n 次,如果 extract(x) 的总时间在该列表远远超过索引新列表所花费的时间。