Python 检测字符串列表中的数字并转换为int
我有一个字符串列表:Python 检测字符串列表中的数字并转换为int,python,python-2.7,nltk,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]和
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类型。使用列表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[:]=…
仅意味着我们更改原始对象/列表。使用带有列表comp的try/except
,尝试强制转换为int
并捕获任何值错误
仅返回中的每个元素,但执行以下操作时
除外:
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[:]=…
仅意味着我们更改原始对象/列表。使用带有列表comp的try/except
,尝试强制转换为int
并捕获任何值错误
仅返回中的每个元素,但执行以下操作时
除外:
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[:]=…
仅意味着我们更改原始对象/列表。使用带有列表comp的try/except
,尝试强制转换为int
并捕获任何值错误
仅返回中的每个元素,但执行以下操作时
除外:
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[:]=…
只意味着我们更改了原始对象/列表