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.

martineau
  • 112,593
  • 23
  • 157
  • 280
  • Does this answer your question? [Convert all strings in a list to int](https://stackoverflow.com/questions/7368789/convert-all-strings-in-a-list-to-int) – Gigioz Dec 14 '20 at 18:25
  • @Gigioz That does not answer the question; the answers on that question do not split on a delimeter. – Aplet123 Dec 14 '20 at 18:25

3 Answers3

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]
Aplet123
  • 30,962
  • 1
  • 21
  • 47
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]

Stan11
  • 264
  • 2
  • 11
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]
Timur Shtatland
  • 9,559
  • 2
  • 24
  • 32