我有一个函数可以确定数字是否小于 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 ]
我如何将上面的函数调用到列表中的数字中?
我是否需要一个循环来对每个列表的每个数字使用该函数,还是比这更简单?
最佳答案
您可以使用 map
和一个 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 指出了这一点) .
关于python - 在列表上使用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23104915/