2

Is there an easy way to convert a list of doubles into a list of lists of doubles?

For example:

[1.0, 2.0, 3.0]

into

[[1.0], [2.0], [3.0]]

The code I'm using requires the second as inputs to a bunch of functions but it's annoying to have two copies of the same data.

Alex Riley
  • 169,130
  • 45
  • 262
  • 238
ad_ad
  • 375
  • 3
  • 14

4 Answers4

18

Just use a list-comprehension wrapping each element in a list:

l = [1.0, 2.0, 3.0]
print [[x] for x in l]
[[1.0], [2.0], [3.0]]
Padraic Cunningham
  • 176,452
  • 29
  • 245
  • 321
2

As an alternative to list comprehensions, you could try map:

>>> map(lambda x: [x], l)
[[1.0], [2.0], [3.0]]

This gives the desired result by applying the lambda function (here, taking an object and putting it in a list) to each element of l in turn.

In Python 3 map returns an iterator so use list(map(lambda x: [x], l)) to get the list.


Using map is about twice as slow as list comprehension for small lists of floats because building the lambda function incurs a small overhead:

>>> %timeit [[x] for x in l]
1000000 loops, best of 3: 594 ns per loop

>>> %timeit map(lambda x: [x], l)
1000000 loops, best of 3: 1.25 us per loop

For longer lists, the time gap between the two starts to close, although list comprehension remains the preferred option in the Python community.

Community
  • 1
  • 1
Alex Riley
  • 169,130
  • 45
  • 262
  • 238
  • *Interestingly*? It seems quite obvious as to why .. Refer http://stackoverflow.com/questions/1247486/python-list-comprehension-vs-map BTW, I like `map` more ;) – Bhargav Rao May 04 '15 at 11:39
  • Thanks for pointing this out - I'd intended the word *interestingly* to mean "worth noting" rather than "mysteriously"... I'll update my answer with a better choice of word and explain the reason why :-) – Alex Riley May 04 '15 at 11:54
  • If you find out a way not to use `lambda` here, then `map` will be faster! – Bhargav Rao May 04 '15 at 11:55
0

It may not be necessary, but if list-comprehensions are cryptic, here's a general solution using a for-loop:

def convert(l):
    converted = []
    if isinstance(l, list):
        if len(l) > 0:
            for n in l:
                converted.append([n])
    return converted

l = [1.0, 2.0, 3.0]
print convert(l)

You could also check wether each element in the list is a float or not, and raise an error if one of them isn't:

class NotFloatError(Exception):

    def __init__(self, message):
        Exception.__init__(self, message)

def convert(l):
    converted = []
    if isinstance(l, list):
        if len(l) > 0:
            for n in l:
                if isinstance(n, float):
                    converted.append([n])
                else:
                    raise NotFloatError("An element in the list is not a float.")
    return converted

l = [1.0, 2.0, 3.0]
print convert(l)
Ericson Willians
  • 7,606
  • 11
  • 63
  • 114
0
a = [1.0, 2.0, 3.0]
for x in a:
    a = [x]
    print a
Denis
  • 390
  • 3
  • 14