python中三重嵌套循环的替代方法

时间:2019-06-05 00:46:27

标签: python for-loop nested

url_list = ['www.scrape.com/file1', 'www.scrape.com/file2', ''www.scrape.com/file3'] 

category_id_list = ['12345','abcde','ABCDE']

zip_list = ['10075','10017','10028']

我使用三个变量来创建要请求的URL。 顺序为:url_list + zip + categoryid

然后将网址传递给具有刮刮代码的函数

我正在使用3个for循环来遍历这些列表,但这是高度冗余的

for url_ in url_list:
   for category_id in category_id_list:
       for zip_ in zip_list:

           request_url = url_+category_zip_
           func(request_url)

这可以完成工作,但是还有更好的方法吗?谢谢!

3 个答案:

答案 0 :(得分:2)

您可以使用itertools.product

import itertools

for url in (str.join("",url) for url in itertools.product(url_list,category_id_list,zip_list)):
    func(url)

答案 1 :(得分:0)

这可能有点晚了,但这是我做到的方式:

cats = ["a","b","c","d"]

zips = ["25320","53902","59607","53123"]

base = "https://example.com"

for i in range(4):
   url = "{}/{}/{}".format(base, cats[i], zips[i])
   print(url)

输出:

https://example.com/a/25320
https://example.com/b/53902
https://example.com/c/59607
https://example.com/d/53123

答案 2 :(得分:0)

一种避免编写多个for循环的方法是使用zip。它允许您一次访问每个列表中的第ith个元素。因此,您可以执行以下操作:

url_list = ['www.scrape.com/file1', 'www.scrape.com/file2', 'www.scrape.com/file3']
category_id_list = ['12345','abcde','ABCDE']
zip_list = ['10075','10017','10028']

for url, id, zip in zip(url_list, category_id_list, zip_list):
    request_url = url + id + zip
    func(request_url)