如何在列表中将str数字转换为int类型?

时间:2020-08-06 09:56:55

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

我是python / python3的新手,试图找出以下内容...

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

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

print(type(new_datalist[0]))

print(type(new_datalist[1]))

<class 'str'>

<class 'str'>

有没有一种方法可以即兴使用数据列表,以使列表中的数字从当前的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'>

3 个答案:

答案 0 :(得分:0)

尝试一下-

PlaygroundSupport.PlaygroundPage.current.needsIndefiniteExecution = true

enum MyError: Error {
    case someError
}
let cancellable = Timer.publish(every: 1, on: .main, in: .default)
    .autoconnect()
    .flatMap({ (input) in
        Just(input)
            .tryMap({ (input) -> String in
                if Bool.random() {
                    throw MyError.someError
                } else {
                    return "we're in the else case"
                }
            })
            .catch { (error) in
                Just("replaced error")
        }
    })
    .sink(receiveCompletion: { (completion) in
        print(completion)
        PlaygroundSupport.PlaygroundPage.current.finishExecution()
    }) { (output) in
        print(output)
}
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]

答案 1 :(得分:0)

您可以制作一个尽可能转换为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]

答案 2 :(得分:0)

您可以使用列表理解来优雅地解决问题。

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