Reputation: 1682
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.
Upvotes: 0
Views: 79
Reputation: 251106
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]
Upvotes: 3
Reputation: 17869
just use list comprehension:
l = [['45.1'], ['21.1'],['42.1']]
my_list = [float(i[0]) for i in l]
>>> my_list
[45.1,21.1,42.1]
Upvotes: 2