2012-12-02 15 views
3

当我试图找出我的BeautifulSoup web刮板的低价格和高价格时,出现此错误。我附上了下面的代码。我的列表不应该是一个整数列表吗?无法排序我的列表,因为它是NoneType?简单的Python

我经历了类似的问题NoneType去张贴此之前,但方案没有工作(!也许我不明白他们)

Traceback (most recent call last): 
    File "/home/user-machine/Desktop/cl_phones/main.py", line 47, in <module> 
    print "Low: $" + intprices[0] 
TypeError: 'NoneType' object is not subscriptable 

相关摘录:

intprices = [] 
newprices = prices[:] 
total = 0 
for k in newprices: 
    total += int(k) 
    intprices.append(int(k)) 

avg = total/len(newprices) 

intprices = intprices.sort() 

print "Average: $" + str(avg) 
print "Low: $" + intprices[0] 
print "High: $" + intprices[-1] 
+0

顺便说一句,你不需要跟踪总共;你可以简单地使用'sum(intprices)',你应该执行'1.0 * sum(intprices)/ len(intprices)'来确保你的平均值有一个小数点。 –

+0

你的回溯中没有什么说你不能对其进行分类。问题是当你试图调用'intprices [0]''''''''''intacices'是'None'时。 –

+0

@Burhan Khalid谢谢,这是一个很好的提示! –

回答

12

intprices.sort()正在排序并返回None,而sorted(intprices)会从您的列表中创建一个全新的排序列表并将其返回。

在你的情况下,因为你不想保持intprices原来的形式只是做intprices.sort()没有重新分配将解决您的问题。

+0

当然,好眼睛。我也排除了这一点。感谢提示,解决了它!只要我被允许,我会尽快选择答案。 –

5

你的问题是该行:

intprices = intprices.sort()

名单上的.sort()方法就地列表上操作,并返回None。只需将其更改为:

intprices.sort()