Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 使用map生成新列表_Python_Python 3.x - Fatal编程技术网

Python 使用map生成新列表

Python 使用map生成新列表,python,python-3.x,Python,Python 3.x,比如说,我有一个x,y坐标的列表,比如: all_coordinates = [x1,y1,x2,y2,x3,y3,x4,y4...] 有一种方法: def rotate_xy_by_theta(self, x, y, theta): # does the maths returns new_x, new_y 对于给定的θ的特定x,y输入值,返回每对坐标的新x,新y位置 现在我想成对地遍历上面列表中的所有项目,并生成一个新的列表modified_坐标 我可以用传统的for循环

比如说,我有一个x,y坐标的列表,比如:

all_coordinates = [x1,y1,x2,y2,x3,y3,x4,y4...]
有一种方法:

def rotate_xy_by_theta(self, x, y, theta):
    # does the maths
    returns new_x, new_y
对于给定的
θ
的特定
x,y
输入值,返回每对坐标的
新x,新y
位置

现在我想成对地遍历上面列表中的所有项目,并生成一个新的列表
modified_坐标

我可以用传统的for循环轻松地实现这一点

这可以通过
map
功能完成吗

比如:

theta = 90    
modified_coordinates = map(self.rotate_xy_by_theta(x, y, theta), all_coordinates)

我的问题是如何在上面的
map
函数中成对地获取
x,y
值。

您不能直接使用
map()
执行您想要的操作,因为您没有对输入中的每个值应用函数。您需要将输入中的值配对,并每次向函数添加一个额外的参数。您的函数还返回一个坐标元组,根据您的需要,您可能需要再次将结果展平

使用中的工具和列表理解是更好的选择:

theta = 90
per_two = zip(*([iter(all_coordinates)] * 2))
modified_coordinates = [self.rotate_xy_by_theta(x, y, theta) for x, y in per_two]
这将为您提供一个
(new_x,new_y)
元组列表,可以说是继续处理的更好格式。如果确实需要再次展平,可以添加另一个循环:

modified_coordinates = [coord for x, y in per_two for coord in self.rotate_xy_by_theta(x, y, theta)]
如果需要将
modified_坐标
作为惰性生成器(如Python 3中的
map()
),可以将其改为生成器表达式:

modified_coordinates = (self.rotate_xy_by_theta(x, y, theta) for x, y in per_two)
或变平:

modified_coordinates = (coord for x, y in per_two for coord in self.rotate_xy_by_theta(x, y, theta))

为什么不使用更好的结构来存储坐标?甚至像
all_坐标=[[x1,x2,x3,x4],[y1,y2,y3,y4].
哦,我希望我能做到。我从一个不受我控制的api中获取
all\u坐标。你可以通过
x\u坐标=all\u坐标[::1]
获取x坐标,通过
y=all\u坐标[1::2]