[英]What is the problem with this simple code using map function in python?
代碼如下:
def func(i,j):
return i+j
m = list(product(range(5),range(7)))
print(m)
x = map(func,m)
list(x)
錯誤 :
[(0, 0), (0, 1), (0, 2), (0, 3), (0, 4), (0, 5), (0, 6), (1, 0), (1, 1), (1, 2), (1, 3), (1, 4), (1, 5), (1, 6), (2, 0), (2, 1), (2, 2), (2, 3), (2, 4), (2, 5), (2, 6), (3, 0), (3, 1), (3, 2), (3, 3), (3, 4), (3, 5), (3, 6), (4, 0), (4, 1), (4, 2), (4, 3), (4, 4), (4, 5), (4, 6)]
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-181-fdda131ed5e8> in <module>()
5 print(m)
6 x = map(func,m)
----> 7 list(x)
TypeError: func() missing 1 required positional argument: 'j'
如何通過func
傳遞m
每一對。 我不想要任何 for 循環。
您可以使用itertools.starmap
:
from itertools import product, starmap
def func(i,j):
return i+j
m = list(product(range(5),range(7)))
print(m)
x = starmap(func,m)
list(x)
...或者您需要不同地定義func()
:
def func(i):
return i[0]+i[1]
在定義( func(i,j)
)中,您傳遞了func()
兩個參數(i, j)
,但僅將map()
func()
map()
到僅參數(元組)。 如果更改func()的定義(在其中傳遞迭代器的位置),則它應該可以工作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.