使用列表上的函数

2024-10-04 11:24:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个函数,它决定数字是小于0还是根本没有数字

def numberfunction(s) :
    if s == "":
        return 0
    if s < 0 :
        return -1
    if s > 0:
        return s

我还有一张单子

numbers = [[]]

现在,假设我在列表中填充了如下数字:

[[1,2,3,4],[1,1,1,1],[2,2,2,2] ..etc ]

我该如何将上面的函数调用到列表中的数字中呢?你知道吗

我需要在每个列表的每个数字上使用函数的循环,还是比这个简单?你知道吗


Tags: 函数列表returnifdefetc数字单子
3条回答

可以使用^{}list comprehension将函数应用于所有元素。请注意,我已经修改了您的示例列表以显示所有退货案例。你知道吗

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]]

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

你可以这样做:

result = [[numberfunction(item) for item in row] for row in numbers]

也可以调用嵌套的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]]
>>> 

我有Python<;3,其中map返回list。你知道吗

相关问题 更多 >