Python 具有多个参数的映射函数到元组列表
Python map function with multiple arguments to a list of tuples
标题可能听起来很奇怪,但这就是我的意思:
def f(x, y, z):
return a_single_number_from_xyz
l = [(10, 'abc', 'def'), (20, 'efg', 'hij')]
print sum([ret_value_of_f_from_first_tuple, ret_value_of_f_from_second_tuple])
function f的三个参数是每个元组的三个元素。
现在,我想将函数 f 应用于列表 l 的每个元组,并希望获得这些单个数字的总和。我如何在一条语句中做到这一点?我如何在这里同时使用映射函数和列表理解?
在这个特殊的案例中,我想你只是想要:
sum(n for n,_,_ in l)
但一般来说,你要找的是itertools.starmap
,所以
list(itertools.starmap(f, iterable))
等同于
[f(*xs) for xs in iterable]
因此 "star" 地图。通常,我会这样做:
sum(f(*xs) for xs in iterable)
对于一般情况,虽然:
sum(itertools.starmap(f, iterable))
对我来说同样优雅。
你可以试试这个:
def f(*args):
return sum(map(lambda x:x[0], args))
l = [(10, 'abc', 'def'), (20, 'efg', 'hij'), (30, "klm", "nop")]
print(f(*l))
输出:
60
如果你需要的只是求和,你可以用这个一行代码得到它:
s = sum(t[0] for t in l)
输出:
>>> l = [(10, 'abc', 'def'), (20, 'efg', 'hij')]
>>> s = sum(t[0] for t in l)
>>> s
30
首先,让我们使用所有值使其成为一个实际的工作函数,例如:
>>> def f(x, y, z):
return x + len(y) + len(z)
现在您的示例数据:
>>> l = [(10, 'abc', 'def'), (20, 'efg', 'hij')]
还有一种方法,给 map 三个可迭代对象(每个 "column" 一个):
>>> sum(map(f, *zip(*l)))
42
哈哈。没看出来。
标题可能听起来很奇怪,但这就是我的意思:
def f(x, y, z):
return a_single_number_from_xyz
l = [(10, 'abc', 'def'), (20, 'efg', 'hij')]
print sum([ret_value_of_f_from_first_tuple, ret_value_of_f_from_second_tuple])
function f的三个参数是每个元组的三个元素。 现在,我想将函数 f 应用于列表 l 的每个元组,并希望获得这些单个数字的总和。我如何在一条语句中做到这一点?我如何在这里同时使用映射函数和列表理解?
在这个特殊的案例中,我想你只是想要:
sum(n for n,_,_ in l)
但一般来说,你要找的是itertools.starmap
,所以
list(itertools.starmap(f, iterable))
等同于
[f(*xs) for xs in iterable]
因此 "star" 地图。通常,我会这样做:
sum(f(*xs) for xs in iterable)
对于一般情况,虽然:
sum(itertools.starmap(f, iterable))
对我来说同样优雅。
你可以试试这个:
def f(*args):
return sum(map(lambda x:x[0], args))
l = [(10, 'abc', 'def'), (20, 'efg', 'hij'), (30, "klm", "nop")]
print(f(*l))
输出:
60
如果你需要的只是求和,你可以用这个一行代码得到它:
s = sum(t[0] for t in l)
输出:
>>> l = [(10, 'abc', 'def'), (20, 'efg', 'hij')]
>>> s = sum(t[0] for t in l)
>>> s
30
首先,让我们使用所有值使其成为一个实际的工作函数,例如:
>>> def f(x, y, z):
return x + len(y) + len(z)
现在您的示例数据:
>>> l = [(10, 'abc', 'def'), (20, 'efg', 'hij')]
还有一种方法,给 map 三个可迭代对象(每个 "column" 一个):
>>> sum(map(f, *zip(*l)))
42
哈哈。没看出来。