【问题标题】:Cast values to integer while filter strings that contain special characters在过滤包含特殊字符的字符串时将值转换为整数
【发布时间】:2017-05-24 11:52:08
【问题描述】:

我的数据包含一长串字符串,我想将它们转换为整数,但仍保留一些包含特殊字符的字符串: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

【问题讨论】:

    标签: python string python-3.x filter


    【解决方案1】:

    根据您的字符串列表,您可以遍历该列表并将所有数值转换为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))
    

    【讨论】:

    • 非常感谢。它可以工作,但是在我的数据列表中,它也有负数,例如:-12、-10 ... 目前,它们的类型也更改为字符串。如何将其保持为 Int?
    • 好的。我懂了。我已经按了“✓”。对不起。我虽然接受投票。
    猜你喜欢
    • 2019-05-02
    • 2020-12-25
    • 2013-03-08
    • 1970-01-01
    • 2018-09-24
    • 2011-08-09
    • 1970-01-01
    • 2015-02-20
    • 2019-02-17
    相关资源
    最近更新 更多