【问题标题】:How to turn str numbers into int type in a list?如何将 str 数字转换为列表中的 int 类型?
【发布时间】:2020-08-06 09:56:55
【问题描述】:

我是这里python/python3的新手,想弄清楚以下...

我有一个包含以下数据的列表:

datalist = ['1','2','abc','def','a234','b456']

print(type(new_datalist[0]))

print(type(new_datalist[1]))

<class 'str'>

<class 'str'>

有没有办法即兴发挥 datalist 使列表中的数字从其当前 str 类型转换为 int 类型?

期望的结果:

new_datalist = []

print(new_datalist)

[1, 2 ,'abc','def','a234','b456']


print(type(new_datalist[0]))

print(type(new_datalist[1]))

<class 'int'>

<class 'int'>

【问题讨论】:

标签: python python-3.x list casting int


【解决方案1】:

试试这个 -

d = [int(i) if i.isnumeric() else i for i in datalist]
print(d)
[1, 2 ,'abc','def','a234','b456']

查看类型 -

[type(i) for i in d]
[int, int, str, str, str, str]

【讨论】:

    【解决方案2】:

    您可以在可能的情况下创建一个转换为 int 的函数:

    def int_or_str(s):
        "try to convert to int, but return string if it fails"
        try:
            return int(s)
        except ValueError:
            return s
    
    new_datalist = [int_or_str(s) for s in datalist]
    

    或者,如果您更喜欢单线,则必须执行以下操作以允许出现负数:

    new_datalist = [int(s)  
                    if s.isnumeric() or (s and s[0] == '-' and s[1:].isnumeric())
                    else s
                    for s in datalist]
    

    你也可以使用正则表达式:

    import re
    
    new_datalist = [int(s) if re.match('-?\d+$', s) else s for s in datalist]
    

    【讨论】:

      【解决方案3】:

      您可以使用列表推导优雅地解决您的问题。

      datalist = [int(data) if data.isdigit() else data for data in datalist]
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-07-19
        • 2019-05-18
        • 2013-08-25
        • 2016-03-12
        • 2020-10-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多