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

detect numbers in a list of strings and convert to int

我有一个字符串列表:

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 转换为类型。

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]

输出是相同的,但 isdigit 不适用于任何负数或 "1.0" 等。使用 strings[:] = ... 仅意味着我们更改原始 object/list.