Python中for循环遍历zip时赋值无效问题求助
Hey there! Let's break down why your second idea isn't working, and clear up what's going on here.
The Core Problem with Idea 2
Your points list starts out completely empty (points = []). When you write:
for point in points: point = label + ":" + str(x) + "," + str(y) + "," + str(z)
This loop never runs at all—there are no elements in points to iterate over! So none of your assignment code gets executed, and points stays empty. That's why printing it later gives nothing.
Why Idea 1 Works
In contrast, points.append(...) directly adds a new element to your empty list every time the outer loop runs. Each iteration builds the string you want and adds it to points, so by the end of the loop, your list is filled with all the combined coordinate-label strings.
A Cleaner Version of Idea 1
By the way, you can make your string formatting much cleaner with Python's f-strings:
x_coord = [23, 53, 2, -12, 95, 103, 14, -5] y_coord = [677, 233, 405, 433, 905, 376, 432, 445] z_coord = [4, 16, -6, -42, 3, -6, 23, -1] labels = ["F", "J", "A", "Q", "Y", "B", "W", "X"] points = [] for x, y, z, label in zip(x_coord, y_coord, z_coord, labels): points.append(f"{label}:{x},{y},{z}") for point in points: print(point)
If You Wanted a "Loop-Assignment" Style (Optional)
If you really wanted to use a loop to populate the list (though append is simpler), you could pre-allocate the list with placeholders first, then iterate over indices:
points = [None] * len(labels) # Create a list with 8 empty slots for idx, (x, y, z, label) in enumerate(zip(x_coord, y_coord, z_coord, labels)): points[idx] = f"{label}:{x},{y},{z}"
This works because now points has elements (even if they're None) to iterate over via their indices, so you can assign values to each position.
内容的提问来源于stack exchange,提问作者kyudope

