[英]User input as a list of integers in python 3
我有这个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))
只要可以隐式转换字符串,就可以始终使用int()
函数将字符串转换为整数。 最常见的是,我将用户输入视为整数,格式如下:
num = int(input("enter a number: "))
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 :> ")]
这样就可以了。
userinput = list(input("Welcome to Cows and Bulls game!!! \nGuess the random 4 digit number :> "))
userinput = [int(i) for i in userinput]
在每次迭代期间,您都可以将输入作为一个整数附加到列表中。
userinput.append(int(input("enter num")))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.