如何遍历一个元组列表并将它们配对?

huangapple go评论52阅读模式
英文:

How to iterate through a list of tuples and make pairs out of them?

问题

我有一个类似这样的列表:

point_list = [(54, 8), (55, 9), (56, 10), (57, 11)]

现在我想将它们配对成:

[(54, 8), (55, 9)], [(55, 9), (56, 10)], [(56, 10), (57, 11)], [(57, 11), (54, 8)]

我有一个函数,它接受两个点的坐标,并返回它们之间的距离。如何将这些成对的点传递给函数并将所有距离附加在一起?

我尝试将元组放入一个列表中,现在我不知道如何继续操作,以便将这些成对的点作为参数传递并将距离附加在一起。

英文:

I have a list like this:

point_list = [(54,8),(55,9),(56,10),(57,11)]

and now I want to make them as pairs like:

[(54,8),(55,9)],[(55,9),(56,10)],[(56,10),(57,11)],[(57,11),(54,8)]

and I have a function which takes in 2 point coordinates and returns the distance between them. How can I pass the individual pairs into the function and append all the distance together?

I did try to get the tuples into a list and now I am stuck on how to move forward from there to pass the pairs as arguments and append the distances.

答案1

得分: 1

你可以使用列表推导式来实现,代码如下:

point_list = [(54,8),(55,9),(56,10),(57,11)]

split_points = [[point_list[i], point_list[(i+1) % len(point_list)]] for i in range(len(point_list))]

print(split_points)

输出结果为:

[[(54, 8), (55, 9)], [(55, 9), (56, 10)], [(56, 10), (57, 11)], [(57, 11), (54, 8)]]

如@JonSG所建议,使用切片的前一种方法可以通过额外的append来实现:

point_list = [(54,8),(55,9),(56,10),(57,11)]

split_points = [point_list[i:i+2] for i in range(len(point_list)-1)]
split_points.append([point_list[-1], point_list[0]])

print(split_points)

要使用点对的坐标,可以像这样操作:

def print_coordinates(x1, y1, x2, y2):
    print(x1, x2, y1, y2)

for point1, point2 in split_points:
    print_coordinates(*point1, *point2)
英文:

You could use list comprehension like so:

point_list = [(54,8),(55,9),(56,10),(57,11)]

split_points = [[point_list[i], point_list[(i+1) % len(point_list)]] for i in range(len(point_list))]

print(split_points)

Output:

[[(54, 8), (55, 9)], [(55, 9), (56, 10)], [(56, 10), (57, 11)], [(57, 11), (54, 8)]]

As suggested by @JonSG, the previous method with splicing would work with an extra append:

point_list = [(54,8),(55,9),(56,10),(57,11)]

split_points = [point_list[i:i+2] for i in range(len(point_list)-1)]
split_points.append([point_list[-1], point_list[0]])

print(split_points)

To use the pairs of points, you could do something like this:

def print_coordinates(x1, y1, x2, y2):
    print(x1, x2, y1, y2)

for point1, point2 in split_points:
    print_coordinates(*point1, *point2)

huangapple
  • 本文由 发表于 2023年3月3日 23:35:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/75629065.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定