我有一些Python代码,它运行一个字符串列表,并将它们转换为整数或浮点数(如果可能的话)。对整数执行此操作非常简单

if element.isdigit():
  newelement = int(element)

浮点数比较难。现在我正在使用partition('.')来分割字符串,并检查以确保一侧或两侧都是数字。

partition = element.partition('.')
if (partition[0].isdigit() and partition[1] == '.' and partition[2].isdigit()) 
    or (partition[0] == '' and partition[1] == '.' and partition[2].isdigit()) 
    or (partition[0].isdigit() and partition[1] == '.' and partition[2] == ''):
  newelement = float(element)

这是可行的,但显然if语句有点麻烦。我考虑的另一个解决方案是将转换封装在一个try/catch块中,看看它是否成功,如这个问题所述。

有人有其他想法吗?对分区和尝试/捕获方法的相对优点有什么看法?


当前回答

传递dictionary作为参数,它将转换可以转换为float的字符串,并保留其他字符串

def covertDict_float(data):
        for i in data:
            if data[i].split(".")[0].isdigit():
                try:
                    data[i] = float(data[i])
                except:
                    continue
        return data

其他回答

我使用了前面提到的函数,但很快我注意到字符串“Nan”,“Inf”和它的变化被认为是数字。所以我建议你改进版本的函数,它将在这些类型的输入上返回false,并且不会失败的“1e3”变体:

def is_float(text):
    # check for nan/infinity etc.
    if text.isalpha():
        return False
    try:
        float(text)
        return True
    except ValueError:
        return False

函数is_digit(str)的简化版本,它在大多数情况下都足够了(不考虑指数符号和“NaN”值):

def is_digit(str):
    return str.lstrip('-').replace('.', '').isdigit()

我会用。

try:
    float(element)
except ValueError:
    print "Not a float"

..这很简单,也很有效。注意,如果元素是例如1<<1024,它仍然会抛出OverflowError。

另一种选择是正则表达式:

import re
if re.match(r'^-?\d+(?:\.\d+)$', element) is None:
    print "Not float"

这就像一个魅力:

[dict([a,int(x) if isinstance(x, str)
 and x.isnumeric() else float(x) if isinstance(x, str)
 and x.replace('.', '', 1).isdigit() else x] for a, x in json_data.items())][0]

你可以使用try-except-else子句,当传递的值不能转换为浮点数时,它将捕获任何转换/值错误


  def try_parse_float(item):
      result = None
      try:
        float(item)
      except:
        pass
      else:
        result = float(item)
      return result