Home > Software engineering >  How to only add positive numeric string to list
How to only add positive numeric string to list

Time:08-04

How to only add positive numeric string to list

lst = '3 -1 0 2 4 2 4 79'
arr = list(map(lambda x: int(x) if int(x) > 0 else None, lst.split()))
print(arr)

this is the answer i get:

[3, None, None, 2, 4, 2, 4, 79]

but i want:

[3, 2, 4, 2, 4, 79]

CodePudding user response:

lst = '3 -1 0 2 4 2 4 79'    
numbers = [int(i) for i in lst.split(' ') if int(i) > 0]

Or you can filter out the None values:

lst = '3 -1 0 2 4 2 4 79'  
arr = list(filter(None, map(lambda x: int(x) if int(x) > 0 else None, lst.split())))

CodePudding user response:

Using filter and map:

lst = '3 -1 0 2 4 2 4 79'

print(list(filter(lambda x: x > 0, map(int, lst.split()))))

Output:

[3, 2, 4, 2, 4, 79]
  • Related