Can';我的列表是非类型的,所以不能排序?简单Python
当我试图计算我的BeautifulSoup网络刮板的价格高低时,我遇到了这个错误。我把代码附在下面。我的列表不应该是INT的列表吗 在发布这篇文章之前,我也遇到过类似的非类型问题,但解决方案不起作用(或者可能我不理解!)Can';我的列表是非类型的,所以不能排序?简单Python,python,list,nonetype,Python,List,Nonetype,当我试图计算我的BeautifulSoup网络刮板的价格高低时,我遇到了这个错误。我把代码附在下面。我的列表不应该是INT的列表吗 在发布这篇文章之前,我也遇到过类似的非类型问题,但解决方案不起作用(或者可能我不理解!) intprices.sort()正在进行排序并返回None,而sorted(intprices)从列表中创建一个全新的排序列表并返回它 在您的情况下,由于您不想保持intprices的原始形式,只需执行intprices.sort(),而不重新分配即可解决问题。您的问题在于:
intprices.sort()
正在进行排序并返回None
,而sorted(intprices)
从列表中创建一个全新的排序列表并返回它
在您的情况下,由于您不想保持
intprices
的原始形式,只需执行intprices.sort()
,而不重新分配即可解决问题。您的问题在于:
intprices=intprices.sort()
列表上的.sort()
方法对就地列表进行操作,并返回None
。只需将其更改为:
intprices.sort()
Dang,好眼力。我也排除了这种可能性。谢谢你的提示,这就解决了问题!我会在允许的情况下尽快选择答案。顺便说一句,你不需要记录总数;你可以简单地sum(intprices)
,你应该做1.0*sum(intprices)/len(intprices)
,以确保你的平均值有一个小数点。回溯中没有任何东西表明你不能排序。问题是当您尝试调用intprices[0]
时,因为intprices
是None
@Burhan Khalid谢谢,这是一个很好的提示!对于非常相似的问题,另一个很好的解释是:
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]