簡體   English   中英

如何以更高效和pythonic的方式編寫以下代碼?

[英]How can I write the following code in a more efficient and pythonic way?

我有一個url列表: file_url_list ,打印到這個:

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

還有另一個Top 1M url的列表: top_url_list ,它打印到:

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

我想找到多少網址在file_url_listtop_url_list 我寫了下面的代碼,但是我知道這不是最快的方法,也不是最pythonic的方法。

# 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)

我怎樣才能以更高效,更pythonic的方式寫出來?

設置交叉應該有幫助。 此外,您可以使用生成器表達式從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çoisFabre

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 ,無論是True還是False 這將分別轉換為10的整數。 url in top_urls for url in file_url_list有效地為sum生成10的序列。

也許稍微更高效(我必須測試它),你可以過濾,如果url in top_urls只加1

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

你可以從第二個列表中獲取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返回一個可迭代的對象,因此您必須執行以下操作:

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

演示

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM