即使我使用int,str类型错误

时间:2017-08-06 18:24:36

标签: python list

请帮帮我。如果用户输入937,程序应该返回973,这是可能的最大数字。

这是我的代码:

list = []
cont = 1
while cont < 4:
    List.append(input(("Type digit ") + str(cont ) + (" of the number: ")))
    cont = cont + 1

print(list)
mayor = int(0)
menor = int(9)
cont = int(0)
while cont < 3:i
    if list[cont] > int(mayor):
        mayor = list[cont]
    if list[cont] < menor:
        menor = list[cont]

    cont = cont + 1

cont  = 0
while cont < 3:
    if list[cont] < mayor:
    if list[cont] > menor:
        m = list[cont]
cont = cont  + 1

list1 = []
list1.append(mayor)
list1.append(m)
list1.append(menor)

print(list1)

这是我得到的错误:

    if list[cont] > int(mayor):    
TypeError: '>' not supported between instances of 'str' and 'int'

2 个答案:

答案 0 :(得分:0)

使用以下方法

list.sort()
m = list[1]

而不是:

cont  = 0
while cont < 3:
    # if list[cont] < mayor:
    if list[cont] > menor:
        m = list[cont]
    cont = cont  + 1

然后尝试:

list = []
cont = 1
while cont < 4:
    list.append(input(("Type digit ") + str(cont ) + (" of the number: ")))
    cont = cont + 1

print(list)

mayor = 0
menor = 9
cont = 0

while cont < 3:
    if int(list[cont]) > int(mayor):
        mayor = list[cont]
    if int(list[cont]) < int(menor):
        menor = list[cont]

    cont = cont + 1

list.sort()
m = list[1] # second largest

list1 = []
list1.append(mayor)
list1.append(m)
list1.append(menor)

print("".join(list1))

输入:

Type digit 1 of the number: 2
Type digit 2 of the number: 5
Type digit 3 of the number: 7

输出

['2', '5', '7']
752

答案 1 :(得分:0)

这就是我解决问题的方法。

list = []
cont = 1
while cont < 4:
    list.append(input(("Ingrese el numero ") + str(cont ) + (" de la cifra: ")))
    cont = cont + 1

print("El numero ingresado es: " , list)
mayor = int(0)
menor = int(9)
cont = int(0)
while cont < 3:
    if int(list[cont]) > int(mayor):
        mayor = list[cont]
    if int(list[cont]) < int(menor):
        menor = list[cont]

    cont = cont + 1

cont  = 0
while cont < 3:
    if list[cont] < mayor:
        if list[cont] > menor:
            m = list[cont]

    cont = cont  + 1

list1 = []
list1.append(mayor)
list1.append(m)
list1.append(menor)

print("El mayor numero possible es: ",list1)