使用map函数进行多重赋值

2 投票
4 回答
850 浏览
提问于 2025-04-17 15:35

可以一次性对多个值使用map函数吗?

就像这样:

from collections import defaultdict
d['a'] = [1,2,3,4]
d['b'] = [4,5,6,7]
d['a'], d['b'] = map(lambda x,y: (x,y) if x*y % 3 == 0 else (0,0), d['a'], d['b'])
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-129-5191c9205e6f> in <module>()
----> 1 d['a'], d['b'] = map(lambda x,y: (x,y) if x*y % 3 == 0 else (0,0), d['a'], d['b'])

ValueError: too many values to unpack

当然,可以对每个值单独进行操作。

 l = map(lambda x,y: x if x*y % 3 == 0 else 0, d['a'],d['b'])
 m = map(lambda x,y: x if x*y % 3 == 0 else 0, d['b'],d['a'])
 d['a'] = l
 d['b'] = m

 d
 defaultdict(<type 'list'>, {'a': [0, 0, 3, 0], 'b': [0, 0, 6, 0]})

4 个回答

0

如果你的参数是整数或浮点数,并且你的函数可以用基本的数学运算来表示,那么你也可以使用数组来实现这个功能。

from numpy import array

x_vals = array([1,2,3,4])
y_vals = array([4,5,6,7])
f = lambda x,y: (x*y % 3 == 0)*x

f(x_vals,y_vals)
>>> array([0, 0, 3, 0])
3

我想不出怎么让 map 函数同时处理两个或更多的值(希望有人能在这个讨论中告诉我)。不过,你可以通过使用列表生成器和 zip 来实现你想要的效果:

from collections import defaultdict

d = {}
d['a'] = [1,2,3,4]
d['b'] = [4,5,6,7]
d['a'], d['b'] = [list(x) for x in zip( *[(x,y) if x*y % 3 == 0 else (0,0) for (x,y) in zip(d['a'], d['b'])])]

如果你不需要 d['a'] 和 d['b'] 是列表的话,可以把最后一行写得简单一点:

d['a'], d['b'] = zip( *[(x,y) if x*y % 3 == 0 else (0,0) for (x,y) in zip(d['a'], d['b'])])
1

是的,你可以用 zip 来实现这个功能。不过,这样做看起来不太像是典型的 Python 风格:

from collections import defaultdict
d = defaultdict(list)
d['a'] = [1,2,3,4]
d['b'] = [4,5,6,7]
d['a'], d['b'] = zip(*map(lambda (x,y): (x,y) if x*y % 3 == 0 else (0,0),
                                                   zip(d['a'], d['b'])))
#out: defaultdict(<type 'list'>, {'a': (0, 0, 3, 0), 'b': (0, 0, 6, 0)})

如果你想得到完全一样的输出:

d['a'], d['b'] = map(list,zip(*map(lambda (x,y): (x,y) if x*y % 3 == 0 else (0,0), 
                                                           zip(d['a'], d['b']))))
#out: defaultdict(<type 'list'>, {'a': [0, 0, 3, 0], 'b': [0, 0, 6, 0]})

撰写回答