[英]Having some problems printing out an array in Python3
我有一個函數,從我的網站上的基本api獲取一個數組,並將其作為文本吐出。
這是功能......
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: -
我不確定為什么這不起作用 - 只是想學習。
在執行中,您有以下內容:
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']))
此外,您在avDates()
中的dates
是一個空列表,您初始化它:
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.