本文介绍了因为是NoneType,所以无法对列表进行排序?简单的Python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我尝试为我的BeautifulSoup网络刮板找出低价和高价时,出现此错误.我附上了下面的代码.我的列表不应该是整数列表吗?

I get this error when I try to figure out the low and high prices for my BeautifulSoup web scraper. I attached the code below. Shouldn't my list be a list of ints?

在发布此消息之前,我经历了类似的NoneType问题,但是解决方案不起作用(或者我听不懂!)

I went through the similar NoneType questions before posting this, but the solutions did not work (or maybe I didn't understand them!)

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]

推荐答案

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

intprices.sort() is sorting in place and returns None, while sorted( intprices ) creates a brand new sorted list from your list and returns it.

在您的情况下,由于您不想保留intprices的原始形式,只需简单地执行intprices.sort()而不进行重新分配就可以解决您的问题.

In your case, since you're not wanting to keep intprices around in its original form simply doing intprices.sort() without reassigning will solve your issue.

这篇关于因为是NoneType,所以无法对列表进行排序?简单的Python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-20 14:23