0

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

pmatos
  • 276
  • 4
  • 18
  • `[int(i) for s in ["1,2","3","4,5"] for i in s.split(",")]` both looks weirder and avoids join-hack at the same time. – tevemadar Feb 11 '22 at 16:41
  • @tevemadar so you are suggesting he make the code more complex, look worse and take longer rather than to use a function that perfectly fits the need? – Eli Harold Feb 11 '22 at 17:05
  • @EliHarold don't bet hastly about the performance, `join()` makes a copy of the strings, and then `split()` makes another, at least in CPython. That may end up being expensive. Anyway, it's simply a generic pattern for flattening, like `[i for s in [[1,2],[3],[4,5]] for i in s]` looks the same and does the same, just for a list of lists instead of a list of strings. – tevemadar Feb 11 '22 at 17:35

2 Answers2

2

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.

Eli Harold
  • 2,280
  • 1
  • 3
  • 22
0

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)
Gleb
  • 33
  • 5