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

Python中普通for循环与列表推导式的区别及代码改写问题

Difference Between List Comprehension and Basic Loop for Pascal's Triangle Initialization

First, let's recap the original Pascal's Triangle generation code we're discussing:

def generate(numRows):
    pascal = [[1]*(i+1) for i in range(numRows)]
    for i in range(numRows):
        for j in range(1,i):
            pascal[i][j] = pascal[i-1][j-1] + pascal[i-1][j]
    return pascal

Key Differences Between the Two Approaches

  • List Comprehension Version: The line [[1]*(i+1) for i in range(numRows)] creates a complete 2D list in one step. It iterates through every i from 0 to numRows-1, generates a row of i+1 ones for each iteration, and collects all these rows into a single list assigned to pascal. By the end of this line, pascal already contains every row of the triangle (all filled with ones), ready to be updated with the correct values.

  • Broken Basic Loop Version: The code for i in range(numRows): pascal = [[1]*(i+1)] has a critical flaw: it overwrites the entire pascal variable on every loop iteration. Instead of building up a list of rows, each loop replaces pascal with a brand-new list that only holds the current row (e.g., when i=2, pascal becomes [[1,1,1]], discarding the rows created for i=0 and i=1). By the end of the loop, pascal will only contain the last row of the triangle.

How to Fix the Basic Loop to Match the List Comprehension

To make the basic loop behave identically to the list comprehension, you need to build the 2D list incrementally instead of overwriting it. Here's the corrected approach:

  1. Start with an empty list to hold all rows of the triangle.
  2. For each i, create the row of i+1 ones and append it to the list, rather than replacing the entire list.

The fixed loop code looks like this:

pascal = []  # Initialize empty list to collect rows
for i in range(numRows):
    pascal.append([1]*(i+1))  # Add each new row to the list instead of overwriting

After running this loop, pascal will be exactly the same as the one created by the original list comprehension. You can then run the nested loop to fill in the middle values just like in the original code.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 11:27:53