Getting only a positive number from a list containing a heterogeneous data type element in python 3

I have a list of elements with disparate data types contained in strings.

lst=['1','err','-1',' ','155'] 

From this, I would like to get a new list with only positive numbers: new_lst=[1,155]

I tried to avoid negative numbers as shown below. However, I cannot escape strings and empty strings:

 lst1=int(lst) for i in lst1: if i<0: print i else: continue Traceback (most recent call last): File "C:/Users/Dev/Documents/Assignment-2/test-2.py", line 22, in <module> c3=int(row[3]) ValueError: invalid literal for int() with base 10: 'err' >>> 
+5
source share
4 answers

lst1=int(lst) is the code that lst1=int(lst) exception. This essentially tries to make a list in int (which you cannot do).

What you want to do is iterate over lst , and for each element, determine if the element can be inserted into int , and then check if the element (like int ) is positive.


You can do something like this:

 lst = ['1','err','-1',' ','155'] new_lst = [] for i in lst: try: int_i = int(i) # try to cast i to an int if int_i > 0: new_lst.append(int_i) except ValueError: # ValueError is raised, i cannot be cast into an int pass # continue to the next element 

EDIT : Added ValueError for completeness, see @BigZ answer.

+2
source
 lst=['1','err','-1',' ','155'] newlst = [] for i in lst: try: if int(i) >= 0: newlst.append(int(i)) except ValueError: pass 
+3
source

Here is one liner that checks if an item is really a number. If this check fails, int(x) will not work, throw and throw away.

 lst=['1','err','-1',' ','155'] lst1 = filter(None,[(lambda x: x if x.isdigit() and int(x) > 0 else None) (x) for x in lst]) 
+2
source

If you just have an int and you think that you want to keep only the positive numbers of str.isdigit , since you don't care if "-1" fails on str.isdigit :

 lst[:] = (ele for ele in lst if ele.isdigit() and int(ele) > 0) 

If you are possibly floats, then all answers using int and try / except will also fail if you want to cover "1.0", etc., you will need to use float in an attempt.

+1
source

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


All Articles