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
>Solution :
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.