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
  • 867
  • 1
  • 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
  • 30,727
  • 7
  • 64
  • 70
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
  • 283,004
  • 58
  • 591
  • 667
0
new_x = []
for elem in x:
    new_x.extend(elem)

This works for any number of elements per sublist.

Rushy Panchal
  • 15,807
  • 15
  • 56
  • 90