检测字符串列表中的数字并转换为int

时间:2015-10-03 15:29:53

标签: python python-2.7 nltk

我有一个字符串列表:

strings = ['stability', 'of', 'the', 'subdural', 'hematoma', 'she', 'was', 'transferred', 'to', 'the', 'neurosciences', 'floor', 'on', '3', '8', 'after', '24', 'hours', 'of', 'close']

什么是迭代列表,检测数字并将元素类型更改为int的最佳方法?

在这个特定的例子中,字符串[13],字符串[14]和字符串[16]应该被识别为数字,并从类型str转换为int类型。

1 个答案:

答案 0 :(得分:3)

try/except与列表组合一起使用,尝试转换为int并抓住任何ValueErrors,只需返回except中的每个元素:

def cast(x):
    try: 
        return int(x)
    except ValueError:
        return x
strings[:] =  [cast(x) for x in strings]

输出:

['stability', 'of', 'the', 'subdural', 'hematoma', 'she', 'was', 
'transferred', 'to', 'the', 'neurosciences', 'floor', 'on', 3, 8, 
'after', 24, 'hours', 'of', 'close']

如果您只有正整数,则可以使用str.isdigit

strings[:] =  [int(x) if x.isdigit() else x for x in strings]

输出结果相同,但是数字不适用于任何负数或"1.0"等。使用strings[:] = ...只是意味着我们更改了原始对象/列表。

相关问题