Modify all elements in a python list and change the type from string to integer

Viewed 449

I have a numerical list which looks like ['3,2,4', '21,211,43', '33,90,87'] I guess at this point the elements are considered as strings.

I want to remove the inverted comas and to make a list which with all these numbers.

Expected output is [3,2,4, 21,211,43, 33,90,87]

Also, I would like to know if the type of element is converted from to string to integer.

Somebody please help me!

3 Answers

What about the following:

result = []
# iterate the string array
for part in ['3,2,4', '21,211,43', '33,90,87']:
    # split each part by , convert to int and extend the final result
    result.extend([int(x) for x in part.split(",")])
print(result)

Output:

$ python3 ~/tmp/so.py 
[3, 2, 4, 21, 211, 43, 33, 90, 87]

There are 3 moving parts here:

  1. splitting a list of strings
  2. converting a string to integer
  3. flattening a nested list

First one, str.split:

>>> '1,2,3'.split(',')
['1', '2', '3']

Second one int:

>>> int('2')
2

And last but not least, list comprehensions:

>>> list_of_lists = [[1,2],[3,4]]
>>> [element for sublist in list_of_lists for element in sublist]
[1, 2, 3, 4]

Putting all three parts together is left as an exercise for you.

>>> your_list = ['3,2,4', '21,211,43', '33,90,87']      
>>> your_list = [int(num) for item in your_list for num in item.split(",")]
>>> print(your_list)
[3, 2, 4, 21, 211, 43, 33, 90, 87]
Related