我有一个字符串列表:
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类型
使用带有list comp的
try/except
,尝试强制转换到int
并捕获任何ValueErrors
只返回except
中的每个元素,当您执行以下操作时:输出:
如果只有正整数,可以使用
str.isdigit
:输出是相同的,但isdigit不适用于任何负数或
"1.0"
等。。使用strings[:] = ...
仅仅意味着我们改变了原始的对象/列表。你知道吗相关问题 更多 >
编程相关推荐