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

Python列表坐标分组输出技术问询:如何实现将列表元素按3个一组提取并格式化输出

Solution to Group List Elements into 3-Element Coordinate Triplets

Alright, let's fix this so we can output all the 3-element coordinate groups from your list instead of just the first one. First, let's break down why your original code only prints 1 2 21:

Your current code only updates x, y, z when the counter hits 0, 1, or 2. After that, the counter keeps increasing but never touches those variables again, and you only print once at the end—so you only get the first three elements.

Here are two straightforward, practical ways to achieve your desired output:

Method 1: Using List Slices with a Step Loop

This approach iterates through the list in chunks of 3, grabbing slices of elements to form each coordinate triplet:

cord = [1,2,21,12,2,44,5,13,15,5,19,21,5]

# Loop through the list starting at index 0, stepping by 3 each time
for i in range(0, len(cord), 3):
    # Grab the current set of 3 elements
    triplet = cord[i:i+3]
    # Format and print the triplet in (x,y,z) style
    if len(triplet) == 3:
        print(f"({triplet[0]}, {triplet[1]}, {triplet[2]})", end=" ")
    else:
        # Optional: Handle incomplete triplets if you need to include them
        print(f"({', '.join(map(str, triplet))})", end=" ")

Output:
(1, 2, 21) (12, 2, 44) (5, 13, 15) (5, 19, 21)
(Note: The final lone 5 is omitted here since it doesn't form a full triplet—remove the if check if you want to include partial groups.)

Method 2: Pythonic Grouping with zip and iter

This is a more concise, idiomatic way to group elements using built-in Python functions:

cord = [1,2,21,12,2,44,5,13,15,5,19,21,5]

# Create three references to the same iterator, so zip pulls 3 elements at a time
for x, y, z in zip(*[iter(cord)]*3):
    print(f"({x}, {y}, {z})", end=" ")

Output:
(1, 2, 21) (12, 2, 44) (5, 13, 15) (5, 19, 21)

This method automatically skips any leftover elements that don't make a full triplet. If you need to include partial groups, you can use itertools.zip_longest (just import itertools first) and set a placeholder for missing values if required.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.30 11:52:33