python - 输入多个以空格分隔的条目
问题描述
我是 python 新手,我有一个任务要编写一个程序,提示用户输入一组以空格分隔的正整数 0、1、...、-1。然后程序只读取和存储正整数并忽略任何无效条目
然后,您的程序应使用以下规则计算将每个数字减为 0 的步骤: • 如果数字是偶数,则将其除以 2 • 如果数字是奇数,则将其减 1
例如,要减少数字 10:
- 10 是偶数,10 除以 2 就变成 5
- 5 为奇数,5 减 1,变为 4 - 4 为偶数,4 除以 2,变为 2
- 2 是偶数,用 2 除以 2 就变成 1
- 1 为奇数,1 减 1,变为 0,所以需要 5 步将 10 减为 0。
到目前为止,在代码中,我可以输入一个条目,但我需要多个以空格分隔的条目。
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)]
请你帮助我好吗?
解决方案
我认为循环的开始是一个问题,因为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)
您可能需要进行更多检查以确保该数字为正数,但这应该可以帮助您入门。
推荐阅读
- latex - 在空白不敏感环境/Z-Notation Schema 中格式化 Latex 中的字符串
- angularjs - 在 AngularJS 和 restangular 中调用 rest API
- python - 如何修复 KeyError:mycode 中的 0
- sql - 计算sql中远程和本地集之间的差异
- python - re.sub 将模板转换为函数
- python-2.7 - 在 Python Shell 错误模块上运行 GrassGIS API 外部运行无
- boolean-logic - 带有嵌套与非门的布尔表达式?
- php - 将旧的 mysql 函数转换为使用 mysqli 扩展
- asp.net-web-api - WebForm 中 Web API 的说明
- python - 读取带有 1 和 0 的 .dat 会返回一些非常奇怪的东西