首页 > 解决方案 > 输入多个以空格分隔的条目

问题描述

我是 python 新手,我有一个任务要编写一个程序,提示用户输入一组以空格分隔的正整数 0、1、...、-1。然后程序只读取和存储正整数并忽略任何无效条目

然后,您的程序应使用以下规则计算将每个数字减为 0 的步骤: • 如果数字是偶数,则将其除以 2 • 如果数字是奇数,则将其减 1

例如,要减少数字 10:

到目前为止,在代码中,我可以输入一个条目,但我需要多个以空格分隔的条目。

stringInput = input("Enter integers: ")
try:
for e in stringInput:
    listOfintegers = []
    stepsCount = 0
    integerInput = int(stringInput)
    integerToTest = integerInput
    while integerToTest > 0:
        if integerToTest % 2 == 0:
            integerToTest /= 2
        else:
            integerToTest -= 1
        stepsCount += 1
    listOfintegers.append((integerInput, stepsCount))
except:
print("a string was entered")
exit(1)

print(listOfintegers)

它应该是这样的:请输入一组以空格分隔的正整数:3 45 st 59 16 32 89

输出:

[(3, 3), (45, 9), (59, 10), (16, 5), (32, 6), (89, 10)]

请你帮助我好吗?

标签: pythonpython-3.xloopsvalidationinput

解决方案


我认为循环的开始是一个问题,因为for e in stringInput:实际上是遍历输入字符串中的每个字符。您可能想要的是遍历每个以空格分隔的条目。有一个很好的功能,split()

split()是一个字符串函数,它将字符串“拆分”成一个列表,其中列表中的每个项目都由您提供的参数分隔。例如,

# x1 is ["1", "2", "3", "4", "5"]
x1 = "1,2,3,4,5".split(",")

# x2 is ["a", "23a", "4a5", "7"]
x2 = "a-23a-4a5-7".split("-")

所以......因为你想用空格分割你的输入字符串,你可能会写类似

stringInput = input("Enter integers: ")

# Splits up input string by spaces
inputList = stringInput.split(" ")
for e in inputList:
    listOfintegers = []
    stepsCount = 0
    integerToTest = 0
    try:
        integerInput = int(stringInput)
        integerToTest = integerInput
    except:
        print("Element is not a number")
        continue
    while integerToTest > 0:
        if integerToTest % 2 == 0:
            integerToTest /= 2
        else:
            integerToTest -= 1
        stepsCount += 1
    listOfintegers.append((integerInput, stepsCount))

print(listOfintegers)

您可能需要进行更多检查以确保该数字为正数,但这应该可以帮助您入门。


推荐阅读