Python实现printSquare函数遇问题求优化:生成前N个数的平方列表
问题分析与解决方案
一、循环代码出错原因
你这段循环的核心问题是混淆了循环变量的含义:
for i in wholeList: x = wholeList[i]**2 tmp.append(x)
当wholeList是[1,2,3,4,5]时,for i in wholeList会让i依次取列表里的元素(1、2、3、4、5),而非列表的索引。你用wholeList[i]相当于用元素值当索引去取值,比如i=5时,wholeList[5]会超出列表索引范围(列表最大索引为4),直接触发IndexError,代码中断后tmp.append(x)自然无法正常执行。
修正后的循环代码:
for i in wholeList: x = i**2 tmp.append(x)
二、简化现有代码
你的getList函数完全没必要单独编写,printSquare可以直接简化为:
def printSquare(num): wholeList = list(range(1, num+1)) # 直接生成1到num的列表 tmp = [] for i in wholeList: tmp.append(i**2) return tmp
调用printSquare(5)即可得到预期输出[1,4,9,16,25]。
三、更高效的写法
Python中最简洁高效的实现方式是列表推导式,一行代码就能完成需求:
def printSquare(num): return [i**2 for i in range(1, num+1)]
如果追求极致性能,也可以用map函数结合lambda实现(可读性稍弱):
def printSquare(num): return list(map(lambda x: x**2, range(1, num+1)))
内容的提问来源于stack exchange,提问作者snoopy dog
相关产品推荐
相关产品推荐

