使用 kwargs 返回 nonetype 的映射 python
map with kwargs returning nonetype python
假设我有一个函数,像这样:
def test(*args, **kwargs):
print(args, kwargs)
我想在地图对象中调用它,像这样:
obj = map(lambda var: test(var+1, var = var), [1, 2, 3])
当我打印其中的值时,显示如下:
>>> for i in obj:
print(i)
(2,) {'var': 1}
None
(3,) {'var': 2}
None
(4,) {'var': 3}
None
None
值来自哪里?
您的映射函数正在打印,而不是 returning 值,因此当您迭代 map
对象时,i
被一遍又一遍地设置为 None
( None
由任何未明确 return
其他功能的函数 return 编辑)。要修复,请将您的函数定义更改为:
def test(*args, **kwargs):
return args, kwargs
所以它 returns 值而不是打印它们,并且你的循环的 print
将看到它们而不是 None
s。
或者,保留函数原样,并将循环更改为:
for i in obj:
pass
所以你不会从 test. This is generally bad style mind you;
map's mapping function should be side-effect free (
printing is a side-effect) to match the functional nature of
map. In general, functions that
printinstead of
[ 打印无用的 None
s =37=]ing are bad ideas; if you
return, the caller can
printif they want to, or use a
returnvalue programmatically, but if you
print`,调用者真的不能做太多(即使他们通过俗气的技巧捕获它,他们被困在解析它以做任何有用的事情)。
您的函数 test
没有 return 任何东西,因此它 return 是 None
。所以在 运行
之后
obj = map(lambda var: test(var+1, var = var), [1, 2, 3])
你实际上会得到 obj
和 [None, None, None]
。
也许您想 return 而不是在您的函数中打印:
def test(*args, **kwargs):
return (args, kwargs)
假设我有一个函数,像这样:
def test(*args, **kwargs):
print(args, kwargs)
我想在地图对象中调用它,像这样:
obj = map(lambda var: test(var+1, var = var), [1, 2, 3])
当我打印其中的值时,显示如下:
>>> for i in obj:
print(i)
(2,) {'var': 1}
None
(3,) {'var': 2}
None
(4,) {'var': 3}
None
None
值来自哪里?
您的映射函数正在打印,而不是 returning 值,因此当您迭代 map
对象时,i
被一遍又一遍地设置为 None
( None
由任何未明确 return
其他功能的函数 return 编辑)。要修复,请将您的函数定义更改为:
def test(*args, **kwargs):
return args, kwargs
所以它 returns 值而不是打印它们,并且你的循环的 print
将看到它们而不是 None
s。
或者,保留函数原样,并将循环更改为:
for i in obj:
pass
所以你不会从 test. This is generally bad style mind you;
map's mapping function should be side-effect free (
printing is a side-effect) to match the functional nature of
map. In general, functions that
printinstead of
[ 打印无用的 None
s =37=]ing are bad ideas; if you
return, the caller can
printif they want to, or use a
returnvalue programmatically, but if you
print`,调用者真的不能做太多(即使他们通过俗气的技巧捕获它,他们被困在解析它以做任何有用的事情)。
您的函数 test
没有 return 任何东西,因此它 return 是 None
。所以在 运行
obj = map(lambda var: test(var+1, var = var), [1, 2, 3])
你实际上会得到 obj
和 [None, None, None]
。
也许您想 return 而不是在您的函数中打印:
def test(*args, **kwargs):
return (args, kwargs)