I have a list like: [['45.1'], ['21.1'],['42.1']]. I think each item is stored as a string here (am I wrong?). I want it look like [45.1,21.1,42.1]. How do I do it? I need to be able to do numerical calculations over these elements of the list.
2 Answers
Use a simple list comprehension:
>>> lis = [['45.1'], ['21.1'],['42.1']]
>>> [float(y) for x in lis for y in x]
[45.1, 21.1, 42.1]
or a faster method using itertools.chain.from_iterable with a list comprehension:
>>> from itertools import chain
>>> [float(x) for x in chain.from_iterable(lis)]
[45.1, 21.1, 42.1]