【问题标题】:What is the most efficient way to run multiple tests in a single loop? Python在一个循环中运行多个测试的最有效方法是什么? Python
【发布时间】:2018-11-23 04:15:16
【问题描述】:

目标:访问博客页面列表。在每个博客页面上,找到该博客页面的社交链接(Instagram、Facebook、Twitter)。

假设:每个社交链接的第一次出现都是正确的。页面后面出现的事件更有可能是指其他人的帐户。

理想的社交 URL 格式是 www.social_network_name.com/username

有些格式的 URL 是不可取的(例如 instagram.com/abc/)

def check_instagram(url):
   if 'instagram.com/' in url and "instagram.com/abc/" not in url::
      return True

def check_facebook(url):
   if 'facebook.com/' in url and "facebook.com/abc/" not in url::
      return True

#my list of pages t be parsed
pages_to_check = ['www.url1.com', 'www.url2.com', ... 'www.urn_n.com']

#iterate through my list of pages t be parsed
for page in pages_to_check :

   #get all the links on the page
   page_links = *<selenium code to get all links on page>*

我试过了……

  For link in page_links:

     #when first Instagram handle found
     if check_instagram(url):
        *code to write to a dataframe here*            
        break

     #when first Instagram handle found
     if check_facebook(url):
        *code to write to a dataframe here*
        break

问题:只要我匹配了一个社交 URL,它就会跳出循环,不再继续寻找其他网络句柄。

如果不是很好,我可以考虑一些选项。我是一个菜鸟。我真的很感激这里的一些建议。

选项 #1 - 遍历所有链接并测试 ONE 社交网络的第一个匹配项。循环遍历所有链接并测试 NEXT 社交网络的第一个匹配项。 (讨厌这个)

选项 #2 - 为每个社交 URL 创建变量。为匹配创建一些标记,并且只更新未设置的匹配变量。 (更好,但我仍然会在填充所有变量后继续迭代)

选项 #3 - 欢迎任何建议或意见。您将如何处理?

【问题讨论】:

  • 如果您不介意额外的空间复杂性,您可以有一个字典来跟踪是否所有社交媒体网址都已处理。 tracker = {'facebook': False, 'instagram': False} 之类的东西;然后每次处理这些社交媒体 URL 时,都会将其对应的值更新为 True。这将允许您仅在字典的所有值都为 True 时才跳出循环。
  • 看看函数filter()。你可以直接过滤page_links

标签: python python-3.x loops processing-efficiency


【解决方案1】:

建议

保留跟踪器并更新任何已处理的社交媒体 URL。一旦它们都被处理完,就跳出循环。

代码

tracker = dict.fromkeys(['facebook', 'instagram'], False)

for link in page_links:
    # if all the values of the tracker are true, then break out of the loop
    if all(v for v in tracker.values()):
        break
    # when first Instagram handle found
    if check_instagram(url):
        *code to write to a dataframe here*
        tracker['instagram'] = True
     # when first Facebook handle found
     if check_facebook(url):
        *code to write to a dataframe here*
        tracker['facebook'] = True

我希望这证明有用。

【讨论】:

  • 非常有用。非常感谢。我唯一添加的内容是在“if check_instagram(url):”之前添加了“if tracker['instagram_found'] == False:”
猜你喜欢
  • 2010-10-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-12-10
  • 2013-10-04
  • 2023-03-29
  • 1970-01-01
相关资源
最近更新 更多