AwayFromMyDesk
AwayFromMyDesk

Reputation: 109

List elements within a list

I generated a list of data from a CSV file. It came out as format as a list within a list:

Wind = [['284'], ['305'], ['335'], ['331'], ['318'], ['303'], ['294'], ['321'], ['324'], ['343']]

I need to list as regular list. So here is my attempt at solving this problem:

i = 0
for ii in Wind:
    Wind[i] = Wind[i][i]
    i += 1
    return Wind

My output is:

return Wind
   ^
SyntaxError: 'return' outside function

Upvotes: 0

Views: 102

Answers (3)

Brionius
Brionius

Reputation: 14098

Another option, using itertools:

import itertools
newWind = list(itertools.chain.from_iterable(Wind))

and another one using numpy:

import numpy
newWind = numpy.array(Wind).transpose()[0].tolist()

and one using a list comprehension that assumes there will always be only one element in the inner lists:

newWind = [x[0] for x in Wind]

and one using map making the same assumption:

newWind = map(lambda x:x[0], Wind)

take your pick!

Upvotes: 1

Matt Bryant
Matt Bryant

Reputation: 4961

You want to flatten the list, which can be done in python using a list comprehension (essentially a shorter, faster, version of a for loop).

Wind = [x for y in Wind for x in y]

The equivalent code using nested for loops would be:

newWind = []
for y in Wind:
    for x in y:
        newWind.append(x)

Upvotes: 2

Jlewis071
Jlewis071

Reputation: 175

The syntax error results because you are trying to execute a return statement when you aren't in a function. If you just want to print the contents of Wind, use print(Wind) instead of return Wind

Upvotes: 0

Related Questions