用户输入为python 3中的整数列表

时间:2018-04-06 15:12:29

标签: python python-3.x list arraylist

我有这个python 3脚本,应该比较两个列表并找到相同的数字。这是一场牛和公牛比赛。不会过多细节,但问题就在这里。当我要求用户输入作为列表时,它返回字符串列表而不是整数,因此如果整数,我无法将元素与给定列表进行比较。请告知如何将userinput列表转换为数字列表:下面的脚本:

import random

numtoguess = [random.randrange(0,10,1) for _ in range (4)]
print(numtoguess)

userinput = []

while numtoguess != userinput:
    userinput = list(input("Welcome to Cows and Bulls game!!! \nGuess the random 4 digit number :> "))
    print(userinput)
    cows = 0
    bulls = 0
    counter = 0
    for i in userinput:
        if i in numtoguess and i == numtoguess[counter]:
            bulls += 1
        elif i in numtoguess and i != numtoguess[counter]:
            cows += 1
        counter += 1
    print('Cows: ' + str(cows))
    print('Bulls: ' + str(bulls))

4 个答案:

答案 0 :(得分:0)

您可以始终使用int()函数将字符串转换为整数,前提是可以隐式转换字符串。最常见的是我将用户输入视为整数,格式如下:

num = int(input("enter a number: "))

答案 1 :(得分:0)

userinput = list(input("Welcome to Cows and Bulls game!!! \nGuess the random 4 digit number :> "))

使用输入字符串的每个字符(数字,但作为字符串)创建一个列表。

只需使用列表推导转换为整数:

userinput = [int(x) for x in input("Welcome to Cows and Bulls game!!! \nGuess the random 4 digit number :> ")]

答案 2 :(得分:0)

好的就是这样。

userinput = list(input("Welcome to Cows and Bulls game!!! \nGuess the random 4 digit number :> "))
userinput = [int(i) for i in userinput]

答案 3 :(得分:0)

在每次迭代期间,您可以将输入作为int ...

附加到列表中
userinput.append(int(input("enter num")))
相关问题