Run 3 variables at once in a python for loop. -
for loop multiple variables in python 2.7.
hello,
i not how go this, have function goes site , downloads .csv file. saves .csv file in particular format: name_uniqueid_datatype.csv. here code
import requests name = "name1" id = "id1" datatype = "type1" def downloaddata(): url = "http://www.website.com/data/%s" %name #downloads file website. last part of url name r = requests.get(url) open("data/%s_%s_%s.csv" %(name, id, datatype), "wb") code: #create file in format name_id_datatype code.write(r.content) downloaddata() the code downloads file , saves fine. want run loop on function takes 3 variables each time. variables written lists.
name = ["name1", "name2"] id = ["id1", "id2"] datatype = ["type1", "type2"] there on 100 different items listed in each list same amount of items in each variable. there way accomplish using loop in python 2.7. have been doing research on better part of day can't find way it. please note new python , first question. assistance or guidance appreciated.
zip lists , use loop:
def downloaddata(n,i,d): name, id, data in zip(n,i,d): url = "http://www.website.com/data/{}".format(name) #downloads file website. last part of url name r = requests.get(url) open("data/{}_{}_{}.csv".format(name, id, data), "wb") code: #create file in format name_id_datatype code.write(r.content) then pass lists function when calling:
names = ["name1", "name2"] ids = ["id1", "id2"] dtypes = ["type1", "type2"] downloaddata(names, ids, dtypes) zip group elements index:
in [1]: names = ["name1", "name2"] in [2]: ids = ["id1", "id2"] in [3]: dtypes = ["type1", "type2"] in [4]: zip(names,ids,dtypes) out[4]: [('name1', 'id1', 'type1'), ('name2', 'id2', 'type2')] so first iteration name,id , data ('name1', 'id1', 'type1') , on..
Comments
Post a Comment