2016-04-12 43 views
1

我有一個函數從我的網站上的基本api獲取數組,並將其作爲文本吐出。在Python3中打印出數組時遇到一些問題

這是函數...

def avDates() : 

import urllib.request 
import json 

response = urllib.request.urlopen('http://www.website.com/api.php') 
content = response.read() 
data = json.loads(content.decode('utf-8')) 
dates = [] 
for i in data: 
    print(str(i['Month'])+": "+str(i['the_days'])) 


return dates 

這個輸出該...

>>> 
Apr: 16, 29, 30 
May: 13, 27 
Jun: 10, 11, 24 
Jul: 08, 22, 23 
Aug: 06, 20 
Sep: 02, 03, 16, 17, 30 
Oct: 01, 14, 15, 29 
Nov: 25 
Dec: 09, 10, 23, 24 
>>> 

所有我想要做的就是打印出以下..

These are the dates: - 
Apr: 16, 29, 30 
May: 13, 27 
Jun: 10, 11, 24 
Jul: 08, 22, 23 
Aug: 06, 20 
Sep: 02, 03, 16, 17, 30 
Oct: 01, 14, 15, 29 
Nov: 25 
Dec: 09, 10, 23, 24 

爲了我可以將它們放入基於文本或HTML的電子郵件腳本中。

我已經通過%s和str()和format()的許多組合,但我似乎無法得到正確的結果。

如果我這樣做...

from availableDates import avDates 
printTest = avDates() 
print ("These are the dates - %s" % ', '.join(map(str, printTest))) 

我得到這個...

Apr: 16, 29, 30 
May: 13, 27 
Jun: 10, 11, 24 
Jul: 08, 22, 23 
Aug: 06, 20 
Sep: 02, 03, 16, 17, 30 
Oct: 01, 14, 15, 29 
Nov: 25 
Dec: 09, 10, 23, 24 
These are the dates: - 

我不知道這是爲什麼不工作 - 只是努力學習。

+0

但是, int'行看起來好像是錯誤的方式? – dazzathedrummer

+0

奇怪的是,如果我將「打印」行註釋掉,只留下導入和變量聲明 - 數組仍然會打印到shell。所以,我認爲,在上面的結果中,數組是從printTest行打印出來的,然後不會打印在打印行中。函數定義中是否有錯誤? – dazzathedrummer

回答

0

在你執行的,則有以下幾點:

from availableDates import avDates 
printTest = avDates() 
print ("These are the dates - %s" % ', '.join(map(str, printTest))) 

但在avDates(),你已經通過一個打印的月度之一:

for i in data: 
    print(str(i['Month'])+": "+str(i['the_days'])) 

此外,您datesavDates()是一個空的列表,你初始化它:

dates = [] 

但從來沒有填充任何東西。因此,在你執行你的了:

Apr: 16, 29, 30 
May: 13, 27 
Jun: 10, 11, 24 
Jul: 08, 22, 23 
Aug: 06, 20 
Sep: 02, 03, 16, 17, 30 
Oct: 01, 14, 15, 29 
Nov: 25 
Dec: 09, 10, 23, 24 

avDates然後

These are the dates: - 

從你最後一次打印您的printTest是一個空列表。

爲了作出正確選擇,你應該在dates把你string,而不是打印出來的並返回dates

def avDates() : 

    import urllib.request 
    import json 

    response = urllib.request.urlopen('http://www.website.com/api.php') 
    content = response.read() 
    data = json.loads(content.decode('utf-8')) 
    dates = [] 
    for i in data: 
     dates.append(str(i['Month'])+": "+str(i['the_days'])) #don't print it yet    
    return dates 

然後在執行:

from availableDates import avDates 
printTest = avDates() 
print ("These are the dates - ") 
for pt in printTest: 
    print (pt) 

然後你應該得到你所期望的:

These are the dates: - 
Apr: 16, 29, 30 
May: 13, 27 
Jun: 10, 11, 24 
Jul: 08, 22, 23 
Aug: 06, 20 
Sep: 02, 03, 16, 17, 30 
Oct: 01, 14, 15, 29 
Nov: 25 
Dec: 09, 10, 23, 24 
+0

這個工程很棒 - 而且是一個非常有用的解釋!謝謝你的幫助!! – dazzathedrummer

+0

@dazzathedrummer沒問題! ;) – Ian