Python 在列表上使用函数

Python 在列表上使用函数,python,list,function,Python,List,Function,我有一个函数,可以确定数字是小于0还是根本没有数字 def numberfunction(s) : if s == "": return 0 if s < 0 : return -1 if s > 0: return s 现在,让我们假设我在列表中填入了如下数字: [[1,2,3,4],[1,1,1,1],[2,2,2,2] ..etc ] 我该如何将上面的函数调到列表中的数字中呢 我需要一个循环,在每个列表

我有一个函数,可以确定数字是小于0还是根本没有数字

def numberfunction(s) :
    if s == "":
        return 0
    if s < 0 :
        return -1
    if s > 0:
        return s
现在,让我们假设我在列表中填入了如下数字:

[[1,2,3,4],[1,1,1,1],[2,2,2,2] ..etc ]
我该如何将上面的函数调到列表中的数字中呢

我需要一个循环,在每个列表的每个数字上使用函数,还是更简单?

您可以这样做:

result = [[numberfunction(item) for item in row] for row in numbers]
可以使用和将函数应用于所有元素。请注意,我已经修改了您的示例列表,以显示所有退货案例

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]]
def number功能:
如果s==“”:
返回0
如果s<0:
返回-1
如果s>0:
返回s
#定义一些示例输入数据。
a=[[1,2,3,”],[-1,1,-1,1],[0,-2,-2,2]]
#将函数应用于每个元素。
b=[a中i的映射(numberfunction,i)]
印刷品(b)
#[1,2,3,0],-1,1,-1,1],[None,-1,-1,2]]

请注意,按照当前
numberfunction
的工作方式,对于等于零的元素,它将返回
None
(感谢@thefourtheye指出这一点)。

您也可以调用嵌套的
map()


我有Python<3,其中map返回list

一件小事,如果
s
0
?@thefourtheye我不知道:(用户没有定义
s==0
的大小写,因此它将返回
None
。我想不喜欢列表理解,+1来自我。@Aश威尼च豪德利,哈哈……真的。谢谢。我想
map
更吸引人P@sshashank124在Python中可能重复@thefourtheye“partial application”?是的,我尝试过@thefourtheye,但我可以使用partial():(@thefourtheye我理解您的代码,我将尝试使用partial,并添加一些谜题,谢谢。
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]]
>>> 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]]
>>>