我怎样才能以一种更有效的方式编写下面的代码?

2024-04-25 06:13:08 发布

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

我有一个URL列表:file_url_list,它打印到:

www.latimes.com, www.facebook.com, affinitweet.com, ...

以及另一个前1M URL的列表:top_url_list,打印到:

[1, google.com], [2, www.google.com], [3, microsoft.com], ...

我想知道file_url_list中有多少个url在top_url_list中。我已经写了下面的代码,但我知道这不是最快的方法,也不是最python的。你知道吗

# Find the common occurrences
found = []
for file_item in file_url_list:
    for top_item in top_url_list:
        if file_item == top_item[1]:
            # When you find an occurrence, put it in a list
            found.append(top_item)

我怎样才能用一种更有效的方式来写呢?你知道吗


Tags: incomurl列表forfacebooktopwww
3条回答

您可以从第二个列表中获取url,然后使用set,正如Kos在他的答案中所示,或者您可以使用lambda和filter。你知道吗

top_url_list_flat = [item[1] for item in top_url_list]
print filter(lambda url: url in file_url_list, top_url_list_flat)

在Python 3中filter返回一个iterable对象,因此必须执行以下操作:

for common in (filter(lambda url: url in file_url_list, top_url_list_flat)):
    print (common)

Demo

设置交叉点应该有帮助。此外,还可以使用生成器表达式从top_url_list中的每个条目中提取url。你知道吗

file_url_list = ['www.latimes.com', 'www.facebook.com', 'affinitweet.com']
top_url_list = [[1, 'google.com'], [2, 'www.google.com'], [3, 'microsoft.com']]

common_urls = set(file_url_list) & set(url for (index, url) in top_url_list)

或者等效地感谢Jean-François Fabre

common_urls = set(file_url_list) & {url for (index, url) in top_url_list}

你说你想知道文件中有多少URL在前1m列表中,而不是它们实际上是什么。构建一组较大的列表(我假设它是1m),然后遍历另一个列表,计算每个列表是否在该集中:

top_urls = {url for (index, url) in top_url_list}
total = sum(url in top_urls for url in file_url_list)

如果文件列表较大,则从该列表生成集合:

file_urls = set(file_url_list)
total = sum(url in file_urls for index, url in top_url_list)

sum将数字相加。url in top_urls求值为bool,可以是TrueFalse。这将分别转换为10整数。url in top_urls for url in file_url_list有效地为sum生成10序列。你知道吗

如果url in top_urls,可能效率稍微高一点(我必须测试它),您可以过滤并只对1进行求和url in top_urls

total = sum(1 for url in file_url_list if url in top_urls)

相关问题 更多 >