3

I have a list of lists:

a = [['0.06'], ['0.54'], ['0.61']] 

I want to convert this list into normal list like this:

a = [0.06, 0.54, 0.61]

How can I do it it

wim
  • 338,267
  • 99
  • 616
  • 750
Anna
  • 101
  • 1
  • 12
  • 2
    Possible duplicate of [Making a flat list out of list of lists in Python](https://stackoverflow.com/questions/952914/making-a-flat-list-out-of-list-of-lists-in-python) – heemayl Jan 10 '18 at 21:05
  • 1
    Wait, this looks like a totally different question – pylang Jan 10 '18 at 22:25
  • @pylang: I am sorry for that... The first comment looked *so* out of place, I decided to check the edits. The OP made it an entirely new question – which goes head on against SO rules. – Jongware Jan 10 '18 at 22:26
  • Which rule does this violate? – pylang Jan 10 '18 at 22:28
  • 2
    I've rolled-back to the version that has existing answers. OP: if you have a different question, please post a new one. – wim Jan 10 '18 at 22:30
  • Wim, good call... I guess I got distracted by looking for precedents on [meta]. @pylang: this "clever" tactic is used by people trying to avoid a question ban. Theybelieve they can ask as many questions as they want, and are not interested in helping a community at large, only themselves. One related Meta discussion (there are pages full of 'em): https://meta.stackoverflow.com/questions/265301/would-it-be-ok-to-change-a-downvoted-question-into-a-completely-different-questi – Jongware Jan 10 '18 at 22:38
  • @pylang: "The edits that completely alter the question are considered **vandalism**." (Even if done by the question asker.) – Jongware Jan 10 '18 at 22:41
  • @wim: thanks. I will notice about this one :) – Anna Jan 11 '18 at 16:23

3 Answers3

3

Using a list comprehension:

>>> a = [['0.06'], ['0.54'], ['0.61']]
>>> [float(x) for [x] in a]
[0.06, 0.54, 0.61]
wim
  • 338,267
  • 99
  • 616
  • 750
  • Can you explain how `[x]` works? I'm unfamiliar with transforming a value within a for statement. – pylang Jan 10 '18 at 22:21
  • This is binding to a `target_list` in the grammar, and is documented [here](https://docs.python.org/3/reference/compound_stmts.html#the-for-statement). – wim Jan 10 '18 at 22:26
  • Wow. That is a gem. Thank you. – pylang Jan 10 '18 at 22:34
2

You can do it with zip() function (returns tuple):

list(zip(*a))[0]

Output: 
('0.06', '0.54', '0.61')

To get list instead of tuple (when you want to modify the list):

list(list(zip(*a))[0])

Output:
['0.06', '0.54', '0.61']
Lukas
  • 2,034
  • 19
  • 27
1

Alternatively, using a functional approach:

list(map(lambda x: float(x[0]), a))
# [0.06, 0.54, 0.61]

Using itertools to first merge the sublists:

import itertools as it


list(map(float, it.chain.from_iterable(a)))
# [0.06, 0.54, 0.61]

A list comprehension is arguably more elegant and clever.

pylang
  • 40,867
  • 14
  • 129
  • 121