我正在接受如下用户输入:0,1,2,3,5 用户可以写任何数字并用逗号分隔,输入将是x,y,z,k,c
然后我无法检查调用split()之后的任何数字是0还是大于30.
代码段:
numbers = input(user[i]['name'] +
", assign 10 different numbers between 1-30 (separate each with a comma ','): ")
usrNums = numbers.split()
for number in usrNums:
if number < 1 or number > 30:
#Something goes here, however, not important now.
P.S。我在all()
上读过一些内容 澄清:用户输入一些数字,例如0,5,2,9,7,10
调用usrNums = numbers.split()
split()
并将其存储在usrNums
中,然后我想检查usrNums [0, 5, 2, 9, 7, 10]
中的每个数字是否有&#34; 0表示数字&lt; ; 1或&gt; 30&#34 ;.
编辑:不,这不是重复,我通读,How can I read inputs as integers in Python?,它根本不是一样的。我的问题是用户输入带有逗号分隔的数字,而不是每个输入一个数字。
答案 0 :(得分:0)
使用拆分时,数字的类型为字符串。要与1或30进行比较,将它们转换为整数
numbers = "0,1,2,3,5"
usrNums = numbers.split(",")
#usrNums ["0","1","2","3","5"]
for number in usrNums:
if int(number) < 1 or int(number) > 30:
答案 1 :(得分:0)
numbers = "1,2,3,31"
for number in numbers.split(","):
number = eval(number) # or use int(number) or float(number) as example
if number < 1 or number > 30:
#do something
你忘了&#34;,&#34;在split函数中忘记将字符串转换为整数。
答案 2 :(得分:0)
您可以使用map()
方法。
numberString = '1, 2, 3, 4, 5, 6, 7'
numbers = map(int, numberString.split(',')) # numbers = [1, 2, 3, 4, 5, 6, 7]
for num in numbers:
if num < 1 or num > 30:
# Do whatever you want here...
希望这有帮助! :)
答案 3 :(得分:-2)
输入是一个字符串。使用levelplot(projected_r)
与eval
进行比较:
int
您还需要指明如何拆分字符串:for number in usrNums:
if eval(number) < 1 or eval(number) > 30:
#Something goes here, however, not important now.