user308827
user308827

Reputation: 21961

extract from each element of list in python

I have the following list:

ll = ['listA_5_val','listB_15_val','listC_25_val']

and I would like to create a new list based on this:

new_list = [5,15,25]

where we have extracted the number from each list. I can do this for a single element like this:

ll[0][6:-4]

How do I do this to entire list?

Upvotes: 1

Views: 70

Answers (4)

Hackaholic
Hackaholic

Reputation: 19733

if there is only one time digit in string:

import re
ll = ['listA_5_val','listB_15_val','listC_25_val']
[ re.findall('\d+',x)[0] for x in ll ]

Upvotes: 1

Cel Skeggs
Cel Skeggs

Reputation: 1877

For each element, one of the better ways would be to use str.split to cut the element into three parts, and then convert the middle part to an integer:

int(element.split("_")[1])

To do this for every element, the most pythonic way would be to use list comprehensions:

new_list = [int(element.split("_")[1]) for element in ll]

Upvotes: 1

Salvador Dali
Salvador Dali

Reputation: 222491

Sure, with a list comprehension it can be done this way:

arr = [int(i[6:-4]) for i in ll]

And will result in: [5, 15, 25]

Upvotes: 1

falsetru
falsetru

Reputation: 368954

Using list comprehension:

>>> ll = ['listA_5_val','listB_15_val','listC_25_val']

>>> [int(x[6:-4]) for x in ll]
[5, 15, 25]

>>> [int(x.split('_')[1]) for x in ll]
[5, 15, 25]

Upvotes: 2

Related Questions