如何从字符串列表中提取数字?

拉布马特

我应该如何仅从中提取数字

a = ['1 2 3', '4 5 6', 'invalid']

我试过了:

mynewlist = [s for s in a if s.isdigit()]
print mynewlist

for strn in a:
    values = map(float, strn.split())
print values

两者均失败,因为数字之间存在空格。

注意:我正在尝试实现以下输出:

[1, 2, 3, 4, 5, 6]
古机器人

我认为您需要将中的每个项目list作为空格上的拆分字符串进行处理。

a = ['1 2 3', '4 5 6', 'invalid']
numbers = []
for item in a:
    for subitem in item.split():
        if(subitem.isdigit()):
            numbers.append(subitem)
print(numbers)

['1', '2', '3', '4', '5', '6']

或以整洁的理解:

[item for subitem in a for item in subitem.split() if item.isdigit()]

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章