简体   繁体   English

在python中,如何拆分元组并作为map函数的单独参数传递

[英]In python, how to split a tuple and pass as separate arguments of map function

Here's what I want to do 这就是我想做的

class Vertex:
  def __init__(self, x,y):
    # ...

coords = [(0,0),(10,10)]
v0, v1 = map(lambda x,y: Vertex(x,y), coords)

The above code won't work, because the coord tuples get passed as x , and there is nothing for y 上面的代码不起作用,因为坐标元组作为x传递,并且y没有任何意义

A workaround that works is 一种可行的解决方法是

class Vertex:
  def __init__(self, x,y):
    # ...

coords = [(0,0),(10,10)]
v0, v1 = map(lambda coord: Vertex(coord[0],coord[1]), coords)

But the first solution looks more elegant to me. 但是第一种解决方案对我来说看起来更优雅。 Probably I've to add an extra step to split the coord tuple. 可能我需要添加一个额外的步骤来拆分coord元组。 How do I do that? 我怎么做?

You can use tuple-unpacking to call the Vertex constructor: 您可以使用tuple-unpacking调用Vertex构造函数:

coord = (0, 0)
Vertex(*coord)

Or for your example: 或举个例子:

v0, v1 = map(lambda coord: Vertex(*coord), coords)

Alternatively, since you are on Python 2, you can also make the lambda accept a tuple: 另外,由于您使用的是Python 2,因此还可以使lambda接受一个元组:

v0, v1 = map(lambda (x, y): Vertex(x, y), coords)

Instead of calling map (which actually returns a generator in Python 3, so your code wouldn't work there), you can also use a list comprehension to create the Vertex objects: 除了调用map (实际上会在Python 3中返回生成器,因此您的代码无法在其中运行)之外,您还可以使用列表推导来创建Vertex对象:

v0, v1 = [Vertex(*coord) for coord in coords]

# or unpack the coordinates as suggested by NPE
v0, v1 = [Vertex(x, y) for x, y in coords]

Just put parentheses around (x, y) : 只需在(x, y)周围加上括号:

v0, v1 = map(lambda (x,y): Vertex(x,y), coords)
#                   ^   ^

Edit: it turns out the above won't work in Python 3 (PEP 3113). 编辑:事实证明以上内容在Python 3(PEP 3113)中不起作用。

The following generator expression will work in both Python 2 and 3: 以下生成器表达式将在Python 2和3中均适用:

v0, v1 = (Vertex(x, y) for x, y in coords)

use zip along with unpack operator *: 解压缩运算符一起使用zip *:

map(Vertex, *zip(*coords))

also, your __init__ signature is possibly wrong, as I assume it misses self argument: 同样,您的__init__签名可能是错误的,因为我认为它缺少self变量:

>>> class Vertex:
...     def __init__(self, x, y):
...         self.x, self.y = x, y
...     def __repr__(self):
...         return 'vertex({}, {})'.format(self.x, self.y)
... 
>>> 
>>> coords = [(1, 2), (3, 4)]
>>> tuple(map(Vertex, *zip(*coords)))
(vertex(1, 2), vertex(3, 4))

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

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