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

How to extract numbers from a list of strings?

我应该如何只从

中提取数字
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

都失败了,因为数字之间有一个 space。

注意:我正在尝试将输出实现为:

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

sets 的帮助下,您可以:

>>> a = ['1 2 3', '4 5 6', 'invalid']
>>> valid = set(" 0123456789")
>>> [int(y) for x in a if set(x) <= valid for y in x.split()]
[1, 2, 3, 4, 5, 6]

如果字符串由 valid 集合中的字符组成,这将包括字符串 中的数字

这应该适用于您的特定情况,因为您在列表中包含了一个字符串。因此你需要把它弄平:

new_list = [int(item) for sublist in a for item in sublist if item.isdigit()]

假设列表只是字符串:

[int(word) for sublist in map(str.split, a) for word in sublist if word.isdigit()]

我认为您需要将 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()]
mynewlist = [s for s in a if s.isdigit()]
print mynewlist

不起作用,因为您正在迭代数组的内容,该数组由三个字符串组成:

  1. '1 2 3'
  2. '4 5 6'
  3. 'invalid'

这意味着您必须对每个字符串再次迭代。

你可以试试

mynewlist = []
for s in a:
    mynewlist += [digit for digit in s if digit.isdigit()] 

一条线解决方案:

new_list = [int(m) for n in a for m in n if m in '0123456789']