简体   繁体   English

如何将元组列表传递给lamda函数

[英]How to pass list of tuple to lamda function

When list of tuples are used in for loop it works perfectly with two separate variables as below 在for循环中使用元组列表时,它与两个单独的变量完美配合,如下所示

t_dict = {
    "k1": "v1",
    "k2": "v2",
    "k3": "v3",
    "k4": "v4",
    "k5": "v5"
}

for k, v in t_dict.items():
    print "%s=%s" % (k, v)

But when converted into lambda with map function got an error as below 但是当使用map函数转换为lambda时出现如下错误

print map(lambda k, v: "%s=%s" % (k, v), t_dict.items())

Traceback (most recent call last):   File "test.py", line 14, in <module>
    print map(lambda k, v: "%s=%s" % (k, v), t_dict.items()) TypeError: <lambda>() takes exactly 2 arguments (1 given)

Is there any other way to call list of tuple in lambda function? 还有其他方法可以在lambda函数中调用元组列表吗?

Built-in map supports multiple iterables: 内置map支持多个可迭代项:

res = map(lambda k, v: "%s=%s" % (k, v), t_dict, t_dict.values())
# ['k1=v1', 'k2=v2', 'k3=v3', 'k4=v4', 'k5=v5']

As described in the docs for map : map文档中所述:

If additional iterable arguments are passed, function must take that many arguments and is applied to the items from all iterables in parallel. 如果传递了其他可迭代参数,则函数必须采用那么多参数,并且并行地将其应用于所有可迭代对象的项。

就您而言,您还可以在%之后使用元组进行格式化,因此:

map(lambda t: "%s=%s" % t, t_dict.items())

As already suggested, you can pass multiple iterables to map , but if you want to pass the items and not keys and values individually, you can use zip(*...) to "transpose" the items to two lists and use * again to pass those as two different arguments to map : 正如已经建议的那样,您可以传递多个iterables来进行map ,但是如果要传递items而不是分别传递keysvalues ,则可以使用zip(*...)将这些项目“转置”到两个列表中,然后再次使用*将它们作为两个不同的参数传递给map

>>> list(map(lambda k, v: "%s=%s" % (k, v), *zip(*t_dict.items())))
['k1=v1', 'k2=v2', 'k3=v3', 'k4=v4', 'k5=v5']

Or use itertools.starmap : 或使用itertools.starmap

>>> from itertools import starmap
>>> list(starmap(lambda k, v: "%s=%s" % (k, v), t_dict.items()))
['k1=v1', 'k2=v2', 'k3=v3', 'k4=v4', 'k5=v5']

Other option is this way ( str.join(iterable) ) to get the list of strings: 另一种选择是这种方式( str.join(iterable) )以获取字符串列表:

map( lambda t: "=".join(t), t_dict.items() )
#=> ['k3=v3', 'k2=v2', 'k1=v1', 'k5=v5', 'k4=v4']

This version can also print out: 此版本也可以打印出来:

import sys
map( lambda t: sys.stdout.write("=".join(t) + "\n"), t_dict.items() )

# k3=v3
# k2=v2
# k1=v1
# k5=v5
# k4=v4

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM