0

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 2

3

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]
Sign up to request clarification or add additional context in comments.

Comments

2

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]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.