有条件地将字符串转换为int

时间:2019-05-28 05:09:26

标签: python casting

在下面的行public class DoublyLinkedList<T> ... { ... private final Class<T> elementClass; ... public DoublyLinkedList(Class<T> elementClass) { this.clazz = elementClass; } ... public boolean remove(Object o) { T data = elementClass.cast(o); ... } ... } 中,如果遇到无法转换为int的值,我想将字符串值保留为string而不是引发异常。有什么优雅的方法可以做到这一点吗?例如,如果您在给定的行data=[int(x) if x else None for x in line.replace("\n","").split(",")]上,则数据将为9327,Garlic Powder,104,13

Rik

[9327, "Garlic Powder", 104, 13]

3 个答案:

答案 0 :(得分:3)

您可以使用isnumeric来保持Oneliner:

data=[int(x) if x and x.isnumeric() else x for x in line.replace("\n","").split(",")]

答案 1 :(得分:2)

尝试一下

>>> def type_convert(var):
    if var.isnumeric():
        return int(var)
    elif isinstance(var, str):
        return var
    else:
        return None


>>> [type_convert(i) for i in a]
[9327, 'Garlic Powder', 104, 13]
>>> new = [type_check(i) for i in a]
>>> [type(n) for n in new]
[<class 'int'>, <class 'str'>, <class 'int'>, <class 'int'>]

答案 2 :(得分:1)

您可以定义一个函数,该函数检查字符串是否可以解析为整数。如果可以,则返回整数,否则返回字符串

def parse(s):

    #If string can be parsed as integer, return integer
    try:
        num = int(s)
        return num
    except:
        pass
    #Else return string
    return s

line = '9327,Garlic Powder,104,13'
data=[parse(x) for x in line.replace("\n","").split(",")]

print(data)

输出将为

[9327, 'Garlic Powder', 104, 13]