10

当我试图找出我的 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]
4

2 回答 2

25

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

就您而言,由于您不想保留intprices其原始形式,因此只需intprices.sort()不重新分配即可解决您的问题。

于 2012-12-02T09:55:30.220 回答
12

你的问题是这条线:

intprices = intprices.sort()

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

intprices.sort()

于 2012-12-02T09:57:02.777 回答