0

我正在尝试在 Python 3 中使用一个巧妙的示例,但在这一行中出现语法错误:

return map(lambda (x, y, an): (x, y), cornersWithAngles)

我已经读过 Python 3 中不允许使用括号解包 lambda 中的参数,但我不知道如何准确地调整我的代码来解决这个问题。

这是完整的代码(错误在第 16 行):

import plotly.plotly as py
import plotly.graph_objs as go
from plotly.tools import FigureFactory as FF

import scipy

def PolygonSort(corners):
    n = len(corners)
    cx = float(sum(x for x, y in corners)) / n
    cy = float(sum(y for x, y in corners)) / n
    cornersWithAngles = []
    for x, y in corners:
        an = (np.arctan2(y - cy, x - cx) + 2.0 * np.pi) % (2.0 * np.pi)
        cornersWithAngles.append((x, y, an))
    cornersWithAngles.sort(key = lambda tup: tup[2])
    return map(lambda (x, y, an): (x, y), cornersWithAngles)

def PolygonArea(corners):
    n = len(corners)
    area = 0.0
    for i in range(n):
        j = (i + 1) % n
        area += corners[i][0] * corners[j][1]
        area -= corners[j][0] * corners[i][1]
    area = abs(area) / 2.0
    return area

corners = [(0, 0), (3, 0), (2, 10), (3, 4), (1, 5.5)]
corners_sorted = PolygonSort(corners)
area = PolygonArea(corners_sorted)

x = [corner[0] for corner in corners_sorted]
y = [corner[1] for corner in corners_sorted]

annotation = go.Annotation(
    x=5.5,
    y=8.0,
    text='The area of the polygon is approximately %s' % (area),
    showarrow=False
)

trace1 = go.Scatter(
    x=x,
    y=y,
    mode='markers',
    fill='tozeroy',
)

layout = go.Layout(
    annotations=[annotation],
    xaxis=dict(
        range=[-1, 9]
    ),
    yaxis=dict(
        range=[-1, 12]
    )
)

trace_data = [trace1]
fig = go.Figure(data=trace_data, layout=layout)

py.iplot(fig, filename='polygon-area')
4

2 回答 2

1

您正在尝试做的事情(参数解包lambda)在 Python 2 中有效,但在 Python 3 中不再有效。

Python 2.7.15rc1 (default, Nov 12 2018, 14:31:15) 
>>> lst = [(1,2,3), (4,5,6), (7,8,9)]
>>> map(lambda (a,b,c): (a,b), lst)
[(1, 2), (4, 5), (7, 8)]

Python 3.6.7 (default, Oct 22 2018, 11:32:17) 
>>> lst = [(1,2,3), (4,5,6), (7,8,9)]
>>> map(lambda (a,b,c): (a,b), lst)
  File "<stdin>", line 1
    map(lambda (a,b,c): (a,b), lst)
               ^
SyntaxError: invalid syntax

不过,您可以做一些事情。

>>> list(map(lambda t: t[:2], lst))
[(1, 2), (4, 5), (7, 8)]
>>> [(a,b) for a, b, c in lst]
[(1, 2), (4, 5), (7, 8)]
>>> from itertools import starmap
>>> list(starmap(lambda a, b, c: (a, b), lst))
[(1, 2), (4, 5), (7, 8)]

就个人而言,我会选择列表理解或生成器表达式。另外,请记住,在 Python 3map中是生成器,而不是列表,因此在使用时,map您可能必须将结果包装在 a 中list,具体取决于您要使用它做什么。

于 2019-02-27T09:57:10.247 回答
1

只需x用作元组,也许这可能会有所帮助:

map(lambda x: (x[0], x[1]), cornerWithEdges)
于 2019-02-27T09:53:37.213 回答