Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

list

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!

like image 997
Rua Goa Avatar asked Nov 17 '20 22:11

Rua Goa


2 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]
like image 106
urban Avatar answered Sep 24 '22 02:09

urban


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.

like image 33
wim Avatar answered Sep 24 '22 02:09

wim