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!
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:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With