How to extract numbers from a list of strings?

最后都变了- 提交于 2019-12-14 03:58:13

问题


How should I extract numbers only from

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

I have tried:

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

and

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]

回答1:


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()]



回答2:


That should do for your particular case since you include a string within list. Therefore you need to flatten it:

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



回答3:


Assuming the list is just strings:

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



回答4:


With the help of sets you can do:

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

This will include the numbers from a string only if the string consists of characters from the valid set.




回答5:


One liner solution:

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



回答6:


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

doesnt work because you are iterating on the content of the array, which is made of three string:

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

that means that you have to iterate again on each of those strings.

you can try something like

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


来源:https://stackoverflow.com/questions/40307848/how-to-extract-numbers-from-a-list-of-strings

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!