Python - TypeError:unorderable类型:str()< INT()

时间:2017-10-27 05:37:49

标签: python

当我尝试运行代码时出现此错误。请帮助,并解释它想说的内容!

此计划旨在为每位候选人找到一个人选票投票偏好(第1,第2,第3等),并删除他们的第一个偏好。第一个偏好被GET https://graph.facebook.com/v2.10/{PAGE_ID}?fields=id,name,**fan_count**,link&access_token={ACCESS_TOKEN}取代,以方便我。

错误:

99999

代码:

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

def countVotes(voteList): candidatePreferences = [] for vote in voteList: minIndex = int(vote.index(min(vote))) candidatePreferences.append(minIndex) vote[minIndex] = 99999 return candidatePreferences 的值(在第一次调用countVotes函数之后):

vList

调用该功能(第二次):

[[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']]

4 个答案:

答案 0 :(得分:0)

Python无法一起订购str值和int值。 在您的示例中,99999int值,而所有其他值都是str值。

答案 1 :(得分:0)

我认为是这行minIndex = int(vote.index(min(vote))) 您正试图在字符串列表中找到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列表后,您可以执行min操作。 请检查并告知我们。

答案 2 :(得分:0)

试试这段代码。它修正了错误:

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]

答案 3 :(得分:0)

将字符串元素转换为整数。您可以使用python map函数将所有列表元素转换为整数

def countVotes(voteList):
    candidatePreferences = []
    for vote in voteList:
        vote = list(map(int, vote)) # add this line to the code to convert string elements to integer
        minIndex = int(vote.index(min(vote)))
        candidatePreferences.append(minIndex)
        vote[minIndex] = 99999
    return candidatePreferences