【问题标题】:User input as a list of integers in python 3用户输入作为python 3中的整数列表
【发布时间】:2018-04-06 15:12:29
【问题描述】:

我有这个 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))

【问题讨论】:

标签: python python-3.x list arraylist


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    好的,这样搞定了。

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

    【讨论】:

    • 您不必转换为list,只需迭代字符即可。
    • @pstatix 与否。如果未来的读者可以从中受益,则可以自行回答问题。
    • 无法删除
    【解决方案3】:
    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 :> ")]
    

    【讨论】:

    • 开枪,你就在我面前得到它。我会删除。
    【解决方案4】:

    在每次迭代期间,您可以将输入作为 int 附加到列表中...

    userinput.append(int(input("enter num")))
    

    【讨论】:

    • 强制用户输入 digit+return x 次。
    猜你喜欢
    • 2019-03-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-19
    相关资源
    最近更新 更多