如何从字符串列表中提取数字? [英] How to extract numbers from a list of strings?

查看:61
本文介绍了如何从字符串列表中提取数字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我应该如何只从

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

都失败了,因为数字之间有空格.

Both failed because there is a space between the numbers.

注意:我试图实现输出为:

Note: I am trying to achieve output as:

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

推荐答案

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

I think you need to process each item in the list as a split string on whitespace.

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']

或者在一个整洁的理解中:

Or in a neat and tidy comprehension:

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

这篇关于如何从字符串列表中提取数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆