在Python的for循环中同时运行3个变量。

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的新手,这是我的第一个问题。任何帮助或指导都将不胜感激。


所以 "name,id,dataType" 重复多次?您想要一个包含这些内容的列表吗? - James Mills
1个回答

7

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')等等。


那个运行得像魔法一样……非常感谢帮助。 - benipy

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接