如何实现numstack函数:让列表中整数按自身数值重复对应次数
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

