将值强制转换为整数,同时筛选包含特殊字符的字符串



我有一长串字符串的数据,我想将它们转换为整数,但仍保留一些包含特殊字符的字符串:x....字符串。有人可以帮我过滤包含特殊字符的字符串吗?

字符串列表:

Type  Values
str   1
str   1
str   1
str   1
str   0
str   10.0.0.21
float nan
str   0
str   38082
str   -10
str   -12
str   0xE0020000

预期类型:

Type  Values
Int   1
Int   1
Int   1
Int   1
Int   0
Str   10.0.0.21
Float nan
Int   0
Int   38082
Int   -10
Int   -12
Str   0xE0020000

给定字符串列表,您可以遍历列表并将所有数值转换为int

input_values = ['1', '1', '1', '1', 
                '0', '10.0.0.21', 
                float('nan'), '0', '38083']
def cast_to_int(word):
    if type(word) == str and word.isnumeric():
        return int(word)
    return word
list(map(cast_to_int, input_values))

更新:

如果input_values中有负值,则需要使用以下解决方案。

def cast_to_int(word):
    try:
        return int(word)
    except ValueError:
        return word
list(map(cast_to_int, input_values))