1

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?

4 Answers 4

2

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]
Sign up to request clarification or add additional context in comments.

Comments

1

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]

Comments

1

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]

Comments

1

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 ]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.