converting python list of strings to their type

后端 未结 7 655
旧时难觅i
旧时难觅i 2020-12-05 19:57

given a list of python strings, how can I automatically convert them to their correct type? Meaning, if I have:

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


        
7条回答
  •  悲&欢浪女
    2020-12-05 20:28

    A variant of ryans's nice solution, for numpy users:

    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
    

提交回复
热议问题