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

Python中for循环遍历zip时赋值无效问题求助

Why Your Second Approach Fails & How to Fix It

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.07 16:42:59