无法对我的列表进行排序,因为它是NoneType?简单的Python

时间:2012-12-02 09:50:56

标签: python list nonetype

当我试图找出BeautifulSoup网络刮刀的低价和高价时,我收到此错误。我附上了以下代码。我的列表不应该是一个整数列表吗?

我在发布之前经历了类似的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]

2 个答案:

答案 0 :(得分:17)

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

在您的情况下,由于您不希望intprices保持原始形式,只需在没有重新分配的情况下执行intprices.sort()即可解决您的问题。

答案 1 :(得分:5)

你的问题就在于:

intprices = intprices.sort()

列表上的.sort()方法在列表中就地运行,并返回None。只需将其更改为:

intprices.sort()