Extract numbers from a list using Regex

Asked

Viewed 1,209 times

2

I have the following list

<type 'list'>: [u'1',u'2'',u'3',u'4',u'7']

The result I hope is:

1 2 3 4 7

I tried to use the re.findall(r'\d+', variavel)

But it doesn’t work, note that I also need

  • 1

    You seem to be confusing some basic concepts - In Python, a ist is a sequence of arbitrary objects. Regexps work for strings, and find statements within text - A string is quite different from a Python object - most objects have a text representation - but this view does not reflect its content. In addition, the re.findall back a list.

3 answers

2


You can do this with the map:

lista = [u'1', u'2', u'3', u'4', u'7']

outraLista = list(map(int, lista))
print (outraLista) # [1, 2, 3, 4, 7]

Or use int to return an entire object:

lista = [u'1', u'2', u'3', u'4', u'7']

outraLista = [int(item) for item in lista if item.isdigit()]
print (outraLista) # [1, 2, 3, 4, 7]

If you want to keep using re.findall, pass the list as a string with str:

import re

lista = [u'1', u'2', u'3', u'4', u'7']

outraLista = re.findall('\d+', str(lista))

for item in outraLista:
    print (item)

1

For lists this way you can do so:

lista = [u'1', u'2', u'5', u'3', u'9', u'1']
result = [x for x in lista if re.match(r"\d+", x) ]

0

You don’t need to use regular expressions for this, only if what you’re looking for is in a large string, then the regex would look for a pattern and return the ones that would marry it..

But if you already have any list and want to extract only the numbers just use a function that checks each element of the list checking whether it is typed or not.

Filter: Runs a function on each element of the list, and filters only those that return true.

>>> lista_qualquer = [u'1',u'2',u'3',u'4',u'7','teste','casa']
>>> e_um_numero = lambda numero : numero:isdigit()
>>> numeros = filter(e_um_numero,lista_qualquer)

And to convert each element of the list only with numbers to integers just use the map performing a function on each element of the list.

>>> numeros = map(int,numeros)
[1,2,3,4,7]

Browser other questions tagged

You are not signed in. Login or sign up in order to post.