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

2024-09-29 19:34:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个字符串列表:

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类型


Tags: oftheto字符串类型列表数字int
1条回答
网友
1楼 · 发布于 2024-09-29 19:34:25

使用带有list comp的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[:] = ...仅仅意味着我们改变了原始的对象/列表。你知道吗

相关问题 更多 >

    热门问题