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 re.findall(r'\d+', variavel)
But it does not work, note that I also need
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 re.findall(r'\d+', variavel)
But it does not work, note that I also need
You can do this with 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 continue using re.findall
, pass the list as a < in> 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)
For lists in this way you can do this:
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) ]
You do not need to use regular expressions for this, only if what you are looking for is in a large string, then the regex would look for a pattern and return those that would marry it.
But if you already have a list and want to extract only the numbers, just use a function that checks each element of the list by checking whether it is a digit or not.
Filter: Performs 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 simply use the map
that executes a function on each element of the list.
>>> numeros = map(int,numeros)
[1,2,3,4,7]