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

2024-04-25 23:42:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我得到这个错误时,我试图找出我的美化组网络刮刀的低和高的价格。我附上了下面的代码。我的单子不应该是一个整数单子吗?

我在发布这篇文章之前,也经历过类似的非类型问题,但是解决方案没有奏效(或者我不理解它们!)

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]

Tags: 代码in网络错误价格整数单子int
2条回答

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

在您的情况下,因为您不想让intprices保持其原始形式,只需在不重新分配的情况下执行intprices.sort()即可解决您的问题。

你的问题是线路:

intprices = intprices.sort()

列表上的.sort()方法对列表进行就地操作,并返回None。把它改成:

intprices.sort()

相关问题 更多 >