0

I have a fairly simple question (I think).

I have a list of lists in python, and the elements are strings. I wish to have a single list, with elements that are floats.

For example:

lst= [['0.0375'], ['-0.1652'], ['0.1841'], ['-0.0304'], ['0.0211'], ['0.1580'], ['-0.0252'], ['-0.0080'], ['-0.0915'], ['0.1208']]

And I need to have something like:

lst= [0.0375, -0.1652, 0.1841, -0.0304, 0.0211, 0.1580, -0.0252, -0.0080, -0.0915, 0.1208]
Mike Graham
  • 73,987
  • 14
  • 101
  • 130
J R
  • 181
  • 1
  • 4
  • 12
  • Is the source list a fixed and constant depth, or is it variable and arbitrary? – Silas Ray Apr 25 '12 at 18:12
  • 2
    You say you want elements which are floats but your final list is made up of strings. Simply calling float on them using the linked-as-duplicate solution would work fine. – DSM Apr 25 '12 at 18:15
  • The source list is a fixed and constant depth. – J R Apr 25 '12 at 18:15
  • 2
    @larsks: only if you already know the term "flatten" – Niklas B. Apr 25 '12 at 18:18
  • 2
    I suspect that Google would lead you to the term "flatten" in a few seconds. E.g., [this](https://www.google.com/search?q=convert+python+list+of+lists+to+single+list). – larsks Apr 25 '12 at 18:19
  • @FrédéricHamidi, That's not quite the same problem (and most of the answerers seem to be quite crazy.) – Mike Graham Apr 25 '12 at 18:28

1 Answers1

2
[float(x) for (x,) in your_list]
Mike Graham
  • 73,987
  • 14
  • 101
  • 130
  • Are you sure about the tuple? It will contain the sublist, so `float()` will fail. Why not `x[0]` instead? – Frédéric Hamidi Apr 25 '12 at 18:28
  • 2
    @FrédéricHamidi, There is no tuple in my code—that `x,` will unpack a length-1 iterable so `x` is the item in each sublist. I use iterable unpacking instead of indexing because it has a subtle advantage of generating an exception instead of failing silently if one day he gets the seemingly-invalid input `[['3'], ['4', '5']]`. – Mike Graham Apr 25 '12 at 18:33
  • Excellent, I was not familiar with that use. I'll keep that in mind, thank you for your explanations :) – Frédéric Hamidi Apr 25 '12 at 18:36