如何以更高效和pythonic的方式编写以下代码?

Ave*_*nus 3 python python-3.x

我有一个url列表:file_url_list,打印到这个:

www.latimes.com, www.facebook.com, affinitweet.com, ...
Run Code Online (Sandbox Code Playgroud)

还有另一个Top 1M url的列表:top_url_list,打印到这个:

[1, google.com], [2, www.google.com], [3, microsoft.com], ...
Run Code Online (Sandbox Code Playgroud)

我想找到多少网址中file_url_list都在top_url_list.我写了下面的代码,但我知道这不是最快的方法,也不是最蟒蛇的方法.

# 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)
Run Code Online (Sandbox Code Playgroud)

我怎样才能以更高效,更pythonic的方式写出来?

Kos*_*Kos 7

设置交叉应该有帮助.此外,您可以使用生成器表达式从中提取每个条目中的URL top_url_list.

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)
Run Code Online (Sandbox Code Playgroud)

或者同样感谢Jean-FrançoisFabre:

common_urls = set(file_url_list) & {url for (index, url) in top_url_list}
Run Code Online (Sandbox Code Playgroud)

  • 使用集合理解:`set(url for(index,url)in top_url_list)`=>`{url for(index,url)in top_url_list}` (3认同)