1

I have this list

['456-789-154','741-562-785','457-154-129']

I want to convert it to int list like this:

[456,789,154,741,562,785,457,154,129]

Please help!!

I tried:

list = [item.replace("-",",") for item in list)
list = [item.replace("'","") for item in list)

But I don't know why the second line is not working.

2
  • Does this answer your question? Convert all strings in a list to int Commented Dec 14, 2020 at 18:25
  • @Gigioz That does not answer the question; the answers on that question do not split on a delimeter. Commented Dec 14, 2020 at 18:25

3 Answers 3

4

Use a double list comprehension:

l = ['456-789-154','741-562-785','457-154-129']
num_list = [int(y) for x in l for y in x.split("-")]
print(num_list) # [456, 789, 154, 741, 562, 785, 457, 154, 129]
Sign up to request clarification or add additional context in comments.

Comments

0

You can use the following approach

my_list = ['456-789-154','741-562-785','457-154-129']
new_list = []
sub_list = []
for item in my_list:
    sub_list = item.split("-")
    for item in sub_list:
        new_list.append(int(item))


print(new_list)

Output

[456, 789, 154, 741, 562, 785, 457, 154, 129]

Comments

0

Use re.findall to return all stretches of digits, then flatten the list of lists and convert to int:

import re
strs = ['456-789-154','741-562-785','457-154-129']
nums = [int(num) for sublist in (re.findall(r'\d+', s) for s in strs) for num in sublist]
print(nums)
# [456, 789, 154, 741, 562, 785, 457, 154, 129]

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.