Remove blank line from list

I just started Python classes and I really need some help. Please keep in mind that I am new if you answer this.

I need to make a program that takes the average of all elements in a specific list of "l". This is a fairly simple function in itself; the problem is that the teacher wants us to delete any blank line present in the list before doing the middle one.

So when I get the list [1,2,3,'',4] , I want the function to ignore the value '' for the average value and just take the average value for the rest 4 / len (l). Can anyone help me with this?

Maybe a loop that saves the comparison of a specific position from the list with '' and removes from the list? I tried this, but it does not work.

+4
source share
7 answers

You can use list comprehension to remove all items '' :

 mylist = [1, 2, 3, '', 4] mylist = [i for i in mylist if i != ''] 

Then you can calculate the average by taking the amount and dividing it by the number of elements in the list:

 avg = sum(mylist)/len(mylist) 

Floating point midpoint (Assuming python 2)

Depending on your application, you might want your average to be a float, not an int. If so, first enter one of these values ​​in the float:

 avg = float(sum(mylist))/len(mylist) 

Alternatively you can use python 3 division:

 from __future__ import division avg = sum(mylist)/len(mylist) 
+13
source

You can use filter() :

filter() returns a list in Python 2 if we pass it a list and iterator in Python 3. As suggested by @PhilH, you can use itertools.ifilter() in Python 2 to get an iterator.

To get the list as output in Python 3, use list(filter(lambda x:x != '', lis))

 In [29]: lis = [1, 2, 3, '', 4, 0] In [30]: filter(lambda x:x != '', lis) Out[30]: [1, 2, 3, 4, 0] 

Note, to filter out any fake value, you can simply use filter(None, ...) :

 >>> lis = [1, 2, 3, '', 4, 0] >>> filter(None, lis) [1, 2, 3, 4] 
+6
source

Other answers show how to create a new list with a deleted item (which is the usual way to do this in python). However, there are times when you want to work with a list in place - here is a way to do this by acting in a list in place:

 while True: try: mylist.remove('') except ValueError: break 

Although I suppose it can be argued that you could do this with a slice assignment and list comprehension:

 mylist[:] = [i for i in mylist if i != ''] 

And, as some of them raised questions about memory usage and the wonders of generators:

 mylist[:] = (i for i in mylist if i != '') 

works too.

+2
source
 itertools.ifilterfalse(lambda x: x=='', myList) 

Iterators are used here, so it does not create a copy of the list and should be more efficient both in time and in memory, which makes it reliable for long lists.

JonClements indicates that this means tracking the length separately, so to display this process:

 def ave(anyOldIterator): elementCount = 0 runningTotal = 0 for element in anyOldIterator: runningTotal += element elementCount += 1 return runningTotal/elementCount 

Or even better

 def ave(anyOldIterator): idx = None runningTotal = 0 for idx,element in enumerate(anyOldIterator): runningTotal += element return runningTotal/(idx+1) 

Decrease:

 def ave(anyOldIterator): pieces = reduce(lambda x,y: (y[0],x[1]+y[1]), enumerate(anyOldIterator)) return pieces[1]/(pieces[0]+1) 

The average time in the range (0.1000) is 10,000 times, gives an understanding of the list for 0.9 s and reduces the version 0.16. So this is already 5 times faster than we add to filtering.

+2
source

You can use:

 alist = ['',1,2] new_alist = filter(None, alist) new_alist_2 = filter(bool, alist) 

Result:

 new_alist = [1,2] new_alist_2 = [1,2] 
+1
source
 mylist = [1, 2, 3, '', 4] newlist = [] for i in mylist: try: newlist.append(int(i)) except ValueError: pass avg = sum(newlist)/len(newlist) 
-1
source

'' is equivalent to False. If we filter the output of 0 (because 0 is equivalent to False), we can use list comprehension:

 [x for x in a if x or x == 0] 

Or, if we strictly want to filter out empty lines :

 [x for x in a if x != ''] 

This may not be the fastest way.

Edit , added some scanner results compared to other solutions (not for the sake of comparison with others, but I was curious which method was the fastest)

 ragsagar> 6.81217217445 pistache> 1.0873541832 cerealy> 1.07090902328 Matt> 1.40736508369 Ashwini Chaudhary> 2.04662489891 Phil H (just the generator) > 0.935978889465 Phil H with list() > 3.58926296234 

I quickly made a script using timeit (), I used [0,1,2,0,3,4,'',5,8,0,'',4] as a list. I conducted several tests, the results did not change.

NOTE. I am not trying to use my solution from above, using speed as a criterion. I know that the OP didn’t specifically request speed, but I was curious and, possibly, some others.

-1
source

Source: https://habr.com/ru/post/1442970/


All Articles