简体   繁体   English

Python用户输入split()和循环

[英]Python user input split() and loop

I am taking user input as follows: 0,1,2,3,5 The user can write any number and separate it with a comma, the input will be x,y,z,k,c 我正在接受用户输入,如下所示:0、1、2、3、5用户可以写任意数字并用逗号分隔,输入将为x,y,z,k,c

Then I am having trouble checking if any of the number after split() is invoked is 0 or more than 30. 然后我在检查split()调用后是否有任何数字为0或大于30时遇到麻烦。

Code-snippet: 程式码片段:

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. 

Ps I've read a little bit on all() 附言:我已经阅读了all()

Clarification: The user inputs some numbers eg 0,5,2,9,7,10 the usrNums = numbers.split() split() is invoked and these are stored in usrNums , then I want to check each number in usrNums [0, 5, 2, 9, 7, 10] if any of them is "0 meaning number < 1 or > 30". 说明:用户输入一些数字,例如0,5,2,9,7,10 usrNums = numbers.split() split()被调用并将它们存储在usrNums ,然后我要检查usrNums [0, 5, 2, 9, 7, 10]每个数字usrNums [0, 5, 2, 9, 7, 10]如果其中任何一个为“ 0表示数字<1或> 30”。

EDIT: NO THIS IS NOT A DUPLICATE, I read through, How can I read inputs as integers in Python? 编辑:没有,这不是重复的,我读完了, 如何在Python中将输入读取为整数? , and it isn't the same at all. ,而且根本不一样。 My question is about user inputting numbers with separated commas, not one number per input. 我的问题是用户输入逗号分隔的数字,而不是每个输入一个数字。

when you use split the numbers are of type string. 使用split时,数字为字符串类型。 To compare with 1 or 30 convert these to integers 要与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: 
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

You forget the "," in the split function and forget to convert the string into an integer. 您忘记了split函数中的“,”,而忘记了将字符串转换为整数。

You can use map() method. 您可以使用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...

Hope this helps! 希望这可以帮助! :) :)

The input is a string. 输入是一个字符串。 Use eval to compare to int : 使用evalint进行比较:

for number in usrNums:
     if eval(number) < 1 or eval(number) > 30: 
     #Something goes here, however, not important now. 

You also need to indicate how to split the string : input.split(',') 您还需要指出如何分割字符串: input.split(',')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM