在python for循环中一次运行3个变量。

贝比

在python 2.7中有多个变量的for循环。

你好,

我不确定该如何处理,我有一个功能可以转到网站并下载.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的新手,这是我的第一个问题。任何帮助或指导将不胜感激。

帕德拉克·坎宁安

压缩列表并使用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和data将('name1', 'id1', 'type1')依此类推。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章