Python 使用map生成新列表
比如说,我有一个x,y坐标的列表,比如: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循环
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]