2016-04-12 44 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