繁体   English   中英

将python字符串列表转换为其类型

[英]converting python list of strings to their type

给定一个python字符串列表,如何自动将它们转换为正确的类型? 意思是,如果我有:

["hello", "3", "3.64", "-1"]

我希望将其转换为列表

["hello", 3, 3.64, -1]  

第一个元素是stirng,第二个是int,第三个是float,第四个是int。

我怎样才能做到这一点? 谢谢。

import ast

L = ["hello", "3", "3.64", "-1"]

def tryeval(val):
  try:
    val = ast.literal_eval(val)
  except ValueError:
    pass
  return val

print [tryeval(x) for x in L]

不使用评估:

def convert(val):
    constructors = [int, float, str]
    for c in constructors:
        try:
            return c(val)
        except ValueError:
            pass
def tryEval(s):
  try:
    return eval(s, {}, {})
  except:
    return s

map(tryEval, ["hello", "3", "3.64", "-1"])

只有在您信任输入时才这样做。 另外,请注意它不仅仅支持文字; 算术表达式也将被评估。

我使用json.loads方法完成了相同的json.loads

def f(l):
    for i in l:
        try:
            yield json.loads(i)
        except:
            yield i

测试:

In [40]: l
Out[40]: ['hello', '3', '3.64', '-1']

In [41]: list(f(l))
Out[41]: ['hello', 3, 3.64, -1]

如果你真的只对字符串,浮点数和整数感兴趣,我更喜欢更冗长,更少的评价

def interpret_constant(c):
    try:
        if str(int(c)) == c: return int(c)
    except ValueError:
        pass
    try:
        if str(float(c)) == c: return float(c)
    except ValueError:
        return c

test_list = ["hello", "3", "3.64", "-1"]

typed_list = [interpret_constant(x) for x in test_list]
print typed_list
print [type(x) for x in typed_list]

这不是一个真正的答案,但我想指出当你有一个带有模式IDPARVAL的参数数据库时,这有多重要。 例如:

ID  PAR      VAL
001 velocity '123.45'
001 name     'my_name'
001 date     '18-dec-1978'

当您不知道需要为特定ID存储多少参数时,此模式是合适的。 缺点恰恰在于VAL中的值都是字符串,需要根据需要转换为正确的数据类型。 您可以通过向架构添加第四列(称为TYPE来执行此操作,也可以使用到目前为止提出的任何方法。

好问题!

PS。 数据库架构与我之前的一个问题相关

对于numpy用户来说,ryans的一个很好的解决方案的变体:

def tonum( x ):
    """ -> int(x) / float(x) / None / x as is """
    if np.isscalar(x):  # np.int8 np.float32 ...
    # if isinstance( x, (int, long, float) ):
        return x
    try:
        return int( x, 0 )  # 0: "0xhex" too
    except ValueError:
        try:
            return float( x )  # strings nan, inf and -inf too
        except ValueError:
            if x == "None":
                return None
            return x

def numsplit( line, sep=None ):
    """ line -> [nums or strings ...] """
    return map( tonum, line.split( sep ))  # sep None: whitespace

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM