比较列表中的元素

use*_*772 2 python list python-3.x

我刚开始学习Python ...我正在编写一个简单的程序,它将采用整数并保留未排序和排序的列表.我遇到排序列表部分的问题...我在比较列表中元素的值时遇到错误.我得到错误的地方是以下行:"if sortedList [sortcount]> sortedList [count]:".我得到"TypeError:unorderable types:list()> int()".

这是代码的一部分......我不确定是什么问题.

numberList = []
sortedList = []
count = 0
sum = 0

....(skip)....

sortcount = 0
sortedList += [ int(userInput) ]
while sortcount < count:
    if sortedList[sortcount] > sortedList[count]:
        sortedList[count] = sortedList[sortcount]
        sortedList[sortcount] = [ int(userInput) ]  
    sortcount+=1
Run Code Online (Sandbox Code Playgroud)

JBe*_*rdo 5

你在哪里做:

sortedList[sortcount] = [ int(userInput) ]
Run Code Online (Sandbox Code Playgroud)

你应该做:

sortedList[sortcount] = int(userInput)
Run Code Online (Sandbox Code Playgroud)

否则你将在该位置添加一个列表并给出你告诉的错误.

顺便说一句,在while循环之前的第一行写入更好

sortedList.append(int(userInput))
Run Code Online (Sandbox Code Playgroud)

  • @JoelCornett:不,JBernardo是完全正确的.OP将sortedList的sortcount-th元素设置为[int(userInput)],这是一个列表.这里没有"添加列表". (2认同)