【问题标题】:Python: Analyzing input to see if its an integer, float, or stringPython:分析输入以查看它是整数、浮点数还是字符串
【发布时间】: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)

【问题讨论】:

    标签: python string


    【解决方案1】:

    如果您从文本文件中读取,您将始终获得字符串,因此您可以使用 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]
    

    【讨论】:

      【解决方案2】:

      您不必将数据转换为字符串并进行处理,您只需使用type 函数获取类型并将结果放入dict 中即可。

      input_list = [100, 234, 'random', 5.23, 55.55, 'random2']
      result = {}
      for item in input_list:
          result.setdefault(type(item), []).append(item)
      print('Integers: ', result[int])
      # Integers:  [100, 234]
      print('Float: ', result[float])
      # Float:  [5.23, 55.55]
      print('Not Numbers', result[str])
      # Not Numbers ['random', 'random2']
      

      【讨论】:

        【解决方案3】:

        其实可以这样检查

         if type(i) is IntType:
           #do something
         if type(i) is StrType:
           #do something
         if type(i) is FloatType:
           #do something
        

        http://docs.python.org/2/library/types.html

        【讨论】:

        • 或者,正如该模块的文档告诉您的那样,您可以使用 intstrfloat 而不是 types 模块:“从 Python 2.2 开始,构建-in 工厂函数,例如 int() 和 str() 也是相应类型的名称。这是现在访问类型而不是使用 types 模块的首选方式。"
        • 比我想象的要容易得多。
        【解决方案4】:

        为那些寻求更小、更优化代码的人提供更好的解决方案

        integer = []
        floats = []
        not_number = []
        full_list = [100, 234, 'random', 5.23, 55.55, 'random2', 'vdfj.324.23tk.sdfklsj']
        
        
        
        for i in full_list:
            if isinstance(i, int):
                integer.append(i)
            elif isinstance(i, float):
                floats.append(i)
            else:
                not_number.append(i)
        print ('Integers ', integer)
        print ('Floats ', floats)
        print ('Not numbers ', not_number)
        

        【讨论】:

          【解决方案5】:

          你可以使用python的eval函数。 要检查输入字符串是否属于什么类型,只需使用 type(eval( your string ))。

          【讨论】:

            猜你喜欢
            • 2018-03-20
            • 2019-10-05
            • 1970-01-01
            • 2022-01-10
            • 1970-01-01
            • 2020-05-05
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多