You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用循环计算列表中多点间的总往返距离

Calculate Total Distance of a Point Loop (Including Return to Start)

Got it, let's walk through how to pull this off step by step. First, make sure we have the required imports since your functions rely on random and math:

import random
import math

First, let's recap your existing functions (I tweaked create_list a bit because the original x_range/y_range parameters were being overwritten immediately—if you intended to use custom ranges, we can adjust that later, but they weren't serving a purpose in your code):

def create_list(locations):
    generated_list = []
    for _ in range(locations):
        x = random.randint(-300, 300)
        y = random.randint(-300, 300)
        generated_list.append([x, y])
    return generated_list

def calculate_distance(starting_x, starting_y, destination_x, destination_y):
    distance = math.hypot(destination_x - starting_x, destination_y - starting_y)
    return distance

Now, to compute the total distance (including the trip back to the starting point), here's a straightforward implementation:

def calculate_total_distance(points):
    total_distance = 0.0
    num_points = len(points)
    
    # Sum distances between consecutive points
    for i in range(num_points - 1):
        start_x, start_y = points[i]
        dest_x, dest_y = points[i+1]
        total_distance += calculate_distance(start_x, start_y, dest_x, dest_y)
    
    # Add the final leg: last point back to the first
    last_x, last_y = points[-1]
    first_x, first_y = points[0]
    total_distance += calculate_distance(last_x, last_y, first_x, first_y)
    
    return total_distance

How to use this:

  1. Generate your list of random points:
    my_points = create_list(5)  # Creates 5 random coordinate points
    print("Generated points:", my_points)
    
  2. Calculate and print the total distance:
    total = calculate_total_distance(my_points)
    print(f"Total loop distance: {total:.2f}")
    

Explanation:

  • We start with a total distance of 0.0 to keep the sum as a float.
  • We loop through each pair of consecutive points (from the first to the second-last), compute their distance, and add it to the total.
  • Finally, we close the loop by adding the distance from the very last point back to the starting point.
  • The :.2f format rounds the result to 2 decimal places for readability—feel free to adjust that or remove it if you want more precision.

If you prefer a more concise version, you can use a generator expression with sum():

def calculate_total_distance(points):
    # Sum consecutive point distances
    consecutive_sum = sum(
        calculate_distance(p1[0], p1[1], p2[0], p2[1])
        for p1, p2 in zip(points, points[1:])
    )
    # Add return to start
    return consecutive_sum + calculate_distance(points[-1][0], points[-1][1], points[0][0], points[0][1])

This does the exact same thing, but uses zip(points, points[1:]) to pair each point with the next one in the list—pick whichever version you find easier to read!


内容的提问来源于stack exchange,提问作者Marzan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.07 09:32:42