Home > Net >  Python list: Extract integers from list of strings
Python list: Extract integers from list of strings

Time:02-12

I have a list with the following values, which in fact are strings inside the list:

mylist = ['4, 1, 2', '1, 2', '120, 13', '223, 10']

How can I extract each value and create a new list with every value inside the list above?

I need a result like:

mylist = [4, 1, 2, 1, 2, 120, 13, 223, 10]

Thank you in advance

CodePudding user response:

Just use a list comprehension like so:

mylist = ['4, 1, 2', '1, 2', '120, 13', '223, 10']
output = [int(c) for c in ",".join(mylist).split(",")]
print(output)

Output:

[4, 1, 2, 1, 2, 120, 13, 223, 10]

This makes a single string of the values and the separates all of the values into individual strings. It then can turn them into ints with int() and add it to a new list.

Credit to: @d.b for the actual code.

CodePudding user response:

I'd offer a solution that is verbose but may be easier to understand

mylist = ['4, 1, 2', '1, 2', '120, 13', '223, 10', '1', '']

separtedList = []
for element in mylist:
    separtedList =element.split(',')

integerList = []
for element in separtedList:
    try:
        integerList.append(int(element))
    except ValueError:
        pass # our string seems not not be an integer, do nothing

mylist = integerList
print(mylist)
  • Related