Python TypeError:无序类型:str()<int()

2024-04-30 03:30:53 发布

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

当我试图运行我的代码时,会出现这个错误。请帮忙,解释一下它想说什么!在

此程序旨在为每个候选人找到一个人的选票偏好(第一、第二、第三等),并删除他们的第一偏好。第一个首选项被99999取代,这样对我来说更容易。在

错误:

ERROR CODE: minIndex = int(vote.index(min(vote)))
TypeError: unorderable types: str() < int()

代码:

^{pr2}$

vList的值(第一次调用countVoices函数后):

[[99999, '3', '4', '5', '2'], ['4', '2', '5', '3', 99999], [99999, '3', '2', '5', '4'], [99999, '2', '4', '3', '5'], [99999, '3', '4', '5', '2'], ['2', 99999, '3', '5', '4'], [99999, '3', '4', '5', '2'], ['3', '5', '2', '4', 99999], [99999, '4', '5', '2', '3'], ['5', 99999, '4', '3', '2'], ['3', '2', '5', '4', 99999], ['3', 99999, '2', '5', '4'], ['2', '5', 99999, '4', '3'], ['3', '2', 99999, '4', '5'], ['4', '5', '3', 99999, '2'], [99999, '5', '4', '3', '2'], [99999, '5', '3', '4', '2'], ['2', 99999, '4', '3', '5'], ['4', 99999, '2', '5', '3']]

调用函数(第二次):

cp = countVotes(vList)

minIndex = int(vote.index(min(vote)))
TypeError: unorderable types: str() < int()

Tags: 代码程序index错误mininttypesvote
3条回答

我想是这条线minIndex=int(投票.索引(分(票))) 您试图在字符串列表中找到min。所以你能做什么

def countVotes(voteList):
    candidatePreferences = []

    for vote in voteList:
         vote = map(int, vote)
         minIndex = int(vote.index(min(vote)))
         candidatePreferences.append(minIndex)
         vote[minIndex] = 99999
   return candidatePreferences

将字符串列表转换为Int list后,可以执行min操作。 请查收并告诉我。在

试试这个代码。它修复了错误:

def countVotes(voteList):
    candidatePreferences = []

    for vote in voteList:
        minIndex = int(vote.index(min(vote)))
        candidatePreferences.append(minIndex)
        vote[minIndex] = '99999'
    return candidatePreferences

vList = [['1', '3', '4', '5', '2'], ['4', '2', '5', '3', '1'], ['1', '3', '2', '5', '4'], ['1', '2', '4', '3', '5'], ['1', '3', '4', '5', '2'], ['2', '1', '3', '5', '4'], ['1', '3', '4', '5', '2'], ['3', '5', '2', '4', '1'], ['1', '4', '5', '2', '3'], ['5', '1', '4', '3', '2'], ['3', '2', '5', '4', '1'], ['3', '1', '2', '5', '4'], ['2', '5', '1', '4', '3'], ['3', '2', '1', '4', '5'], ['4', '5', '3', '1', '2'], ['1', '5', '4', '3', '2'], ['1', '5', '3', '4', '2'], ['2', '1', '4', '3', '5'], ['4', '1', '2', '5', '3']]
cp = countVotes(vList)
print(str(cp))

output:
[0, 4, 0, 0, 0, 1, 0, 4, 0, 1, 4, 1, 2, 2, 3, 0, 0, 1, 1]

Python不能将str值和int值一起排序。 在您的示例中,99999是一个int值,而所有其他值都是str值。在

相关问题 更多 >