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

如何实现numstack函数:让列表中整数按自身数值重复对应次数

Fixing Your numstack(n) Function

Hey there, let's break down why your current code isn't producing the right result, then fix it with a couple of straightforward solutions.

The Problem with Your Current Code

Looking at your code:

def numstack(n):
    for i in range(1,n+1):
        z = [i]*i
    return z
print(numstack(3))

The issue is that you're reassigning z entirely in each loop iteration. By the time the loop finishes, z only holds the value from the last iteration (when i = n). For numstack(3), that means you end up with [3,3,3] instead of the expected [1,2,2,3,3,3].

Solution 1: Build the List Gradually with extend()

Instead of overwriting z each time, initialize an empty list and add each set of repeated numbers to it using extend():

def numstack(n):
    result = []
    for i in range(1, n + 1):
        result.extend([i] * i)  # Adds all elements of [i]*i to the end of result
    return result

print(numstack(4))  # Output: [1, 2, 2, 3, 3, 3, 4, 4, 4, 4]

extend() takes an iterable (like your [i]*i list) and appends each element from it to the main list—perfect for building up your desired sequence step by step.

Solution 2: Use a Nested List Comprehension (Shorter Version)

If you prefer more concise code, a nested list comprehension does the same job in one line:

def numstack(n):
    return [num for num in range(1, n + 1) for _ in range(num)]

print(numstack(3))  # Output: [1, 2, 2, 3, 3, 3]

Here, the outer loop iterates over each number from 1 to n, and the inner loop runs num times, adding num to the list each time. It's a clean, Pythonic way to create the sequence you need.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.29 09:12:51