重复直到返回值不为None的Pythonic方法

时间:2019-07-02 08:09:54

标签: python python-3.x

我有一个URL列表,其中某些URL可能无效。我想从一个随机选择的URL收集图像。如果URL或图像无效,则get_image_from_url函数将返回None。因此,我要重复行get_image_from_url(random.choice(urls)),直到它不返回None。因为urls可能是一个很大的列表,所以我不想为以前的完整列表过滤掉无效的url。我做了以下事情:

image = None
while not image:
    image = ImageNetUtilities.get_image_from_url(random.choice(urls))

return image

我想知道是否有更好的(更Python化的)方法来实现我的目标。我正在使用Python3。

编辑

根据评论中的建议,我应该删除所有已经选择的网址。我替换了

image = ImageNetUtilities.get_image_from_url(random.choice(urls))

image = ImageNetUtilities.get_image_from_url(urls.pop(random.randrange(len(urls))))

1 个答案:

答案 0 :(得分:2)

一个版本,1)如果所有 URL均无效,则可避免无限循环; 2)仅对每个URL进行一次测试; 3)使用凉爽的Python功能的版本如下:

image = next(filter(None, map(ImageNetUtilities.get_image_from_url, random.sample(urls, k=len(urls)))))

您也可以事先random.sample(urls, k=len(urls))来代替random.shuffle

要对此加以区分:

相关问题