Domanda

I have an excel file with many lines of data, but also many blank spaces. The main problem is that I have my regular average for one day's data on top of my weighted average followed by many blank spaces to the next day. So when I pull it out using xlrd I get a very messy array.

I think I know how to get rid of the blank spaces, but my list has some data that no weighted average for that day. So I need to search my list and delete any value that does not have a space after it, then search back through the list and delete all the spaces.

For example I want this:

[754, 753.554, '', '', '', '', '', 653.455, '', '', 258, 235.6464, '' , '', '']

to return:

[753.554, 653.455, 235.6464]

Any advice?

È stato utile?

Soluzione

>>> l = [754, 753.554, '', '', '', '', '', 653.455, '',
         '', 258, 235.6464, '' , '', '']
>>> filter(None, [i for i, j in zip(l, l[1:] + ['']) if j == ''])
[753.554, 653.455, 235.6464]

Altri suggerimenti

Actually this is enough:

data = filter(None, [754, 753.554, '', '', '', '', '', 653.455, '', '', 258, 235.6464, '' , '', ''])

Assuming that weighted average will be floating numbers:

filter(lambda x: not isinstance(x, int),filter(None, a))

But you can also replace lambda x: not isinstance(x, int) with a function:

def is_not_weight_avg(x):
    # do stuff here
    # if it is w. avg.
    return x 

and then you can write the above line as:

filter(is_weight_avg,filter(None, a)). 

This is a little bit of functional programming in Python. Explanation:

b=range(1,11)

def is_odd(x):
   if x % 2:
      return 0
   else:
      return x
filter(is_odd, b)
>>> [2, 4, 6, 8, 10]
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top