I have a function that determines if the number is less than 0 or if there isn't a number at all
def numberfunction(s) :
if s == "":
return 0
if s < 0 :
return -1
if s > 0:
return s
i also have a list of lists
numbers = [[]]
now, lets say i filled the list of lists with numbers like:
[[1,2,3,4],[1,1,1,1],[2,2,2,2] ..etc ]
how would i go about calling up the function i had above into the numbers i have in the lists?
Would I require a loop where I use the function on every number of every list, or is it simpler than that?
You can use map and a list comprehension to apply your function to all of your elements. Please note that I have modified your example list to show all of the return cases.
def numberfunction(s) :
if s == "":
return 0
if s < 0 :
return -1
if s > 0:
return s
# Define some example input data.
a = [[1,2,3,""],[-1,1,-1,1],[0,-2,-2,2]]
# Apply your function to each element.
b = [map(numberfunction, i) for i in a]
print(b)
# [[1, 2, 3, 0], [-1, 1, -1, 1], [None, -1, -1, 2]]
Note that, with the way your numberfunction works at the moment, it will return None for an element equal to zero (thanks to @thefourtheye for pointing this out).
You can also call nested map():
>>> a = [[1,2,3,""],[-1,1,-1,1],[2,-2,-2,2]]
>>> map(lambda i: map(numberfunction, i), a)
[[1, 2, 3, 0], [-1, 1, -1, 1], [2, -1, -1, 2]]
>>>
I have Python < 3 in which map returns list.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With