2016-11-24 181 views
1

我有这样让for循环蟒蛇返回intergers

for i in view_overall_isp_ratings: 
     #the int and the round is just for casting the values returned 
     me = (int(round(i.avg_of_ratings))) 
     print(me) 

and this prints intergers like this 1 
            1 
            1 
            1 
            4 

for循环蟒蛇我想要什么

for it to produce a list like this 
    [ 1 ,1 ,1 ,1 ,4] 

试图用[],但至少玩弄的列表我可以得到是

[1] 
[1] 
[1] 
[1] 
[4] 

任何人都可以协助

回答

1

您需要创建一个列表,并追加到它在每次循环迭代(循环外!):

lst = [] 
for i in view_overall_isp_ratings: 
    #the int and the round is just for casting the values returned 
    lst.append(int(round(i.avg_of_ratings))) 

print(lst) 

或者,在一个更清洁的方式,你可以使用列表理解:

print([int(round(i.avg_of_ratings)) for i in view_overall_isp_ratings]) 
+1

你已经拯救了一个灵魂,这绝对有效,我想我现在需要拥抱更pythonic的思维方式.... – Chamambom