Python 输入多个以空格分隔的条目

Python 输入多个以空格分隔的条目,python,python-3.x,loops,validation,input,Python,Python 3.x,Loops,Validation,Input,我是python新手,我的任务是编写一个程序,提示用户输入一组空格分隔的正整数我认为循环的开始是一个问题,正如stringInput中e的所说:实际上是遍历输入字符串中的每个字符。您可能想要的是,通过每个空格分隔的条目。有一个很好的函数,split() split()。比如说, x1是[“1”、“2”、“3”、“4”、“5”] x1=“1,2,3,4,5”。拆分(“,”) #x2为[“a”、“23a”、“4a5”、“7”] x2=“a-23a-4a5-7”。拆分(“-”) 所以…既然你想用空格

我是python新手,我的任务是编写一个程序,提示用户输入一组空格分隔的正整数我认为循环的开始是一个问题,正如stringInput中e的
所说:
实际上是遍历输入字符串中的每个字符。您可能想要的是,通过每个空格分隔的条目。有一个很好的函数,
split()

split()。比如说,

x1是[“1”、“2”、“3”、“4”、“5”] x1=“1,2,3,4,5”。拆分(“,”) #x2为[“a”、“23a”、“4a5”、“7”] x2=“a-23a-4a5-7”。拆分(“-”)
所以…既然你想用空格分割你的输入字符串,你可能会写这样的东西

stringInput=input(“输入整数:”)
#按空格拆分输入字符串
inputList=stringInput.split(“”)
对于输入列表中的e:
积分列表=[]
StepScont=0
integerToTest=0
尝试:
integerInput=int(stringInput)
integerToTest=integerInput
除:
打印(“元素不是数字”)
持续
当integerToTest>0时:
如果integerToTest%2==0:
integerToTest/=2
其他:
integerToTest-=1
StepScont+=1
追加((integerInput,StepScont))
打印(整数列表)

您可能需要做更多的检查以确保数字为正数,但这应该可以让您开始了。

我认为循环的开始是一个问题,正如stringInput中的e所说:实际上是在遍历输入字符串中的每个字符。您可能想要的是,通过每个空格分隔的条目。有一个很好的函数,
split()

split()。比如说,

x1是[“1”、“2”、“3”、“4”、“5”] x1=“1,2,3,4,5”。拆分(“,”) #x2为[“a”、“23a”、“4a5”、“7”] x2=“a-23a-4a5-7”。拆分(“-”)
所以…既然你想用空格分割你的输入字符串,你可能会写这样的东西

stringInput=input(“输入整数:”)
#按空格拆分输入字符串
inputList=stringInput.split(“”)
对于输入列表中的e:
积分列表=[]
StepScont=0
integerToTest=0
尝试:
integerInput=int(stringInput)
integerToTest=integerInput
除:
打印(“元素不是数字”)
持续
当integerToTest>0时:
如果integerToTest%2==0:
integerToTest/=2
其他:
integerToTest-=1
StepScont+=1
追加((integerInput,StepScont))
打印(整数列表)

您可能需要做更多的检查以确保数字为正数,但这应该可以让您开始了。

您只需使用
split()
命令,例如
split(“”
)按空格分割输入

我修改了你的代码

#stringInput = "3 45 st 59 16 32 89"
stringInput = input("Enter integers: ")
stringInput=stringInput.split(" ")
listOfintegers = []

for e in stringInput:
    stepsCount = 0
    if(e.isdigit()):
        integerInput = int(e)
    else:
        continue
    integerToTest = integerInput
    while integerToTest > 0:
        if integerToTest % 2 == 0:
            integerToTest /= 2
        else:
            integerToTest -= 1
        stepsCount += 1
    listOfintegers.append((integerInput, stepsCount))

print(listOfintegers)

您只需使用
split()
命令,例如
split(“”)
按空格分割输入

我修改了你的代码

#stringInput = "3 45 st 59 16 32 89"
stringInput = input("Enter integers: ")
stringInput=stringInput.split(" ")
listOfintegers = []

for e in stringInput:
    stepsCount = 0
    if(e.isdigit()):
        integerInput = int(e)
    else:
        continue
    integerToTest = integerInput
    while integerToTest > 0:
        if integerToTest % 2 == 0:
            integerToTest /= 2
        else:
            integerToTest -= 1
        stepsCount += 1
    listOfintegers.append((integerInput, stepsCount))

print(listOfintegers)

非常感谢你的帮助。我真的在为如何分割输入而挣扎,所以谢谢你教我命令谢谢你的帮助。我真的在为如何分割输入而挣扎,所以谢谢你教我命令谢谢你的帮助!非常感谢你的帮助!我非常感激