为了判断输入是整数、 float 还是字符串,我已经为此研究了一两天。
简而言之,该程序旨在将每个输入转换为一个字符串,遍历每个字符串并检查列表中的数字。如果字符串的所有数字都是整数,如果它有一个“。”它是一个 float ,如果没有则不是数字。明显的缺陷是包含字母和“.”的字符串。在此程序中将被视为 float 。
这个程序的最终目标是打开文本文件并查看输入是 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)
请您参考如下方法:
如果您从文本文件中读取,您将始终得到字符串,因此您可以使用 int() 和 float() 来决定每个元素属于哪种类型并捕获异常:
integers = []
floats = [] # Don't use float as a variable, it will override a built-in python function
not_number = []
# I modified this list so all the elements are string, if you already have ints and floats, you can use type() to know where to append
input_list = ["100", "234", 'random', "5.23", "55.55", 'random2']
for i in input_list:
value = None
try:
value = int(i)
except ValueError:
try:
value = float(i)
except ValueError:
not_number.append(i)
else:
floats.append(value)
else:
integers.append(value)
print(not_number)
print(floats)
print(integers)
# ['random', 'random2']
# [5.23, 55.55]
# [100, 234]
