python中的方块列表 [英] List of squares in python

查看:75
本文介绍了python中的方块列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要写一个前n个平方数的函数,平方序列以1、4、9、16、25开始.

I need to write a function of the first n square numbers, The sequence of squares start with 1, 4, 9, 16, 25.

例如,如果输入为16,则输出为

For example if the input is 16, the output will be

[1, 4, 9, 16, 25, 36, 49, 64, 81, 100, 121, 144, 169, 196, 225, 256] 

这段代码是我尝试过的,但是完全错误.这段代码会将我的电话号码从1计数到255.我不知道该怎么解决

This code is what I've tried, but its completely wrong. This code counts my number from 1 to 255. I have no idea what to fix

def squares(n):
    L = list(range(n**2))
    L = [num for num in L if num]
    return L

推荐答案

使用列表理解:

def squares(n):
    L = [i*i for i in range(1,n+1)]
    return L

print (squares(16))

输出:

[1, 4, 9, 16, 25, 36, 49, 64, 81, 100, 121, 144, 169, 196, 225, 256]

这篇关于python中的方块列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆