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.
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]]
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 .
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)
a = [1.0, 2.0, 3.0]
for x in a:
a = [x]
print a
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.