【发布时间】:2019-02-04 17:55:45
【问题描述】:
为了判断输入是整数、浮点数还是字符串,我已经为此工作了一两天。
简而言之,该程序旨在将每个输入转换为一个字符串,循环遍历每个字符串并检查列表数字。如果字符串的所有数字都是整数,如果它有一个“。”它是一个浮点数,如果没有,则不是数字。明显的缺陷是包含字母和 '.' 的字符串。在此程序中将被视为浮点数。
此程序的最终目标是打开文本文件并查看输入是 int、float 还是其他类型。
问题
-有什么办法可以进一步优化这个程序
-如何进一步修改此程序以打开文本文件,读取、分析和写入哪个输入在哪个列表中
第一次发帖!!!
#Checks input to see if input is integer, float, or character
integer = []
float = []
not_number = []
digits = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
input_list = [100, 234, 'random', 5.23, 55.55, 'random2']
for i in input_list:
i = str(i)
length = len(i)
count = 0
marker = 0
for j in i:
for k in digits:
if k == j:
count = count + 1
#k loops through digits to see if j single character
#string input is number
if count == length:
integer.append(i)
marker = 1
#count is equal to length if entire string is integers
if j == '.':
float.append(i)
marker = 1
#Once '.' is found, input is "considered" a float
if marker == 1:
break
else:
not_number.append(i)
#If code above else proves that input is not a number the
#only result is that it isn't a number
print ('Integers: ', integer)
print ('Float: ', float)
print ('Not Numbers', not_number)
【问题讨论】: