我有一个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)
我怎样才能用一种更有效的方式来写呢?你知道吗
您可以从第二个列表中获取url,然后使用
set
,正如Kos在他的答案中所示,或者您可以使用lambda和filter。你知道吗在Python 3中
filter
返回一个iterable对象,因此必须执行以下操作:Demo
设置交叉点应该有帮助。此外,还可以使用生成器表达式从
top_url_list
中的每个条目中提取url。你知道吗或者等效地感谢Jean-François Fabre:
你说你想知道文件中有多少URL在前1m列表中,而不是它们实际上是什么。构建一组较大的列表(我假设它是1m),然后遍历另一个列表,计算每个列表是否在该集中:
如果文件列表较大,则从该列表生成集合:
sum
将数字相加。url in top_urls
求值为bool
,可以是True
或False
。这将分别转换为1
或0
整数。url in top_urls for url in file_url_list
有效地为sum
生成1
或0
序列。你知道吗如果
url in top_urls
,可能效率稍微高一点(我必须测试它),您可以过滤并只对1
进行求和url in top_urls
:相关问题 更多 >
编程相关推荐