簡體   English   中英

在python for循環中一次運行3個變量。

[英]Run 3 variables at once in a python for loop.

在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') ,依此類推。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM