在python for循环中一次运行3个变量. [英] Run 3 variables at once in a python for loop.
问题描述
在python 2.7中具有多个变量的For循环.
For loop with multiple variables in python 2.7.
你好,
我不确定该怎么做,我有一个功能可以转到网站并下载.csv文件.它将以特定格式保存.csv文件:name_uniqueID_dataType.csv.这是代码
I am not certain how to go about this, I have a function that goes to a site and downloads a .csv file. It saves the .csv file in a particular format: name_uniqueID_dataType.csv. here is the code
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循环.变量将被写为列表.
The code downloads the file and saves it perfectly fine. I want to run a for loop on the function that takes those three variables each time. The variables will be written as lists.
name = ["name1", "name2"]
id = ["id1", "id2"]
dataType = ["type1", "type2"]
每个列表中将列出100多个不同的项目,并且每个变量中的项目数量相同.有什么方法可以在python 2.7中使用for循环来完成此操作.我一天中的大部分时间都在进行研究,但我找不到解决方法.请注意,我是python的新手,这是我的第一个问题.任何帮助或指导将不胜感激.
There will be over 100 different items listed in each list with the same amount of items in each variable. Is there any way to accomplish this using a for loop in python 2.7. I have been doing research on this for the better part of a day but I can't find a way to do it. Please note that I am new to python and this is my first question. Any assistance or guidance would be greatly appreciated.
推荐答案
zip 列表并使用for循环:
zip the lists and use a for loop:
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)
然后在调用时将列表传递给您的函数:
Then pass the lists to your function when calling:
names = ["name1", "name2"]
ids = ["id1", "id2"]
dtypes = ["type1", "type2"]
downloadData(names, ids, dtypes)
zip将按索引对元素进行分组:
zip will group your elements by 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')]
因此,第一个迭代名称,id和数据将为('name1', 'id1', 'type1')
,依此类推.
So the first iteration name,id and data will be ('name1', 'id1', 'type1')
and so on..
这篇关于在python for循环中一次运行3个变量.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!