2

I'm new to python. How is possible to transform an array like this:

x=[[0.3], [0.07], [0.06]]

into:

x=[0.3,0.07, 0.06]

? Thanks in advance.

Marika Blum
  • 907
  • 2
  • 8
  • 7

3 Answers3

5

The following list comprehension may be useful.

>>> x=[[0.3], [0.07], [0.06]]
>>> y = [a for [a] in x]
>>> y
[0.3, 0.07, 0.06]

Considering that the inner values are of type list too.

A similar but more readable code, as given by cdhowie is as follows.

>>> x=[[0.3], [0.07], [0.06]]
>>> y = [a[0] for a in x]
>>> y
[0.3, 0.07, 0.06]
Community
  • 1
  • 1
Sukrit Kalra
  • 33,167
  • 7
  • 69
  • 71
4

This is a classic use of itertools.chain.from_iterable

from itertools import chain
print list(chain.from_iterable(x))

Where this example really shines is when you have an iterable with arbitrary length iterables inside it:

[[0],[12,15],[32,24,101],[42]]
mgilson
  • 300,191
  • 65
  • 633
  • 696
0
new_x = []
for elem in x:
    new_x.extend(elem)

This works for any number of elements per sublist.

Rushy Panchal
  • 16,979
  • 16
  • 61
  • 94