for python 2.7中包含多个变量的循环。
你好,
我不确定如何解决此问题,我有一个功能可以访问网站并下载.csv文件。它以特定格式保存.csv文件:name_uniqueID_dataType.csv。这是代码
import requests
name = "name1"
id = "id1"
dataType = "type1"
def downloadData():
URL = "http://www.website.com/data/%s" %name #downloads the file from the website. The last part of the URL is the name
r = requests.get(URL)
with open("data/%s_%s_%s.csv" %(name, id, dataType), "wb") as code: #create the file in the format name_id_dataType
code.write(r.content)
downloadData()
代码下载文件并完全保存。我想在每次获取这三个变量的函数上运行for循环。变量将写为列表。
name = ["name1", "name2"]
id = ["id1", "id2"]
dataType = ["type1", "type2"]
每个列表中将列出100多个不同的项目,每个变量中的项目数量相同。有没有办法在python 2.7中使用for循环来实现这一点。我一整天都在研究这个问题,但我找不到办法。请注意我是python的新手,这是我的第一个问题。任何协助或指导将不胜感激。
答案 0 :(得分:5)
zip列表并使用for循环:
def downloadData(n,i,d):
for name, id, data in zip(n,i,d):
URL = "http://www.website.com/data/{}".format(name) #downloads the file from the website. The last part of the URL is the name
r = requests.get(URL)
with open("data/{}_{}_{}.csv".format(name, id, data), "wb") as code: #create the file in the format name_id_dataType
code.write(r.content)
然后在调用时将列表传递给您的函数:
names = ["name1", "name2"]
ids = ["id1", "id2"]
dtypes = ["type1", "type2"]
downloadData(names, ids, dtypes)
zip将按索引对元素进行分组:
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')]
因此,第一个迭代名称,id和数据将为('name1', 'id1', 'type1')
,依此类推..