Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using functions on lists

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?

like image 835
SammyHD Avatar asked Sep 23 '26 11:09

SammyHD


2 Answers

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).

like image 75
Ffisegydd Avatar answered Sep 25 '26 23:09

Ffisegydd


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.

like image 39
Grijesh Chauhan Avatar answered Sep 26 '26 01:09

Grijesh Chauhan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!