l = [x**0.5 for x in range(101)]
print l
此代码输出:
[0.0, 1.0, 1.4142135623730951, 1.7320508075688772, 2.0, 2.23606797749979, 2.449489742783178, 2.6457513110645907, 2.8284271247461903, 3.0, 3.162277660168379, 3.3166247903554, 3.4641016151377544, 3.605551275463989, 3.7416573867739413, 3.872983346207417, 4.0, 4.123105625617661, 4.242640687119285, 4.358898943540674, 4.47213595499958, 4.58257569495584, 4.69041575982343, 4.795831523312719, 4.898979485566356, 5.0, 5.0990195135927845, 5.196152422706632, 5.291502622129181, 5.385164807134504, 5.477225575051661, 5.567764362830022, 5.656854249492381, 5.744562646538029, 5.830951894845301, 5.916079783099616, 6.0, 6.082762530298219, 6.164414002968977, 6.244997998398398, 6.324555320336758, 6.4031242374328485, 6.48074069840786, 6.557438524302, 6.6332495807108, 6.708203932499369, 6.782329983125268, 6.855654600401044, 6.928203230275509, 7.0, 7.0710678118654755, 7.14142842854285, 7.211102550927978, 7.280109889280518, 7.3484692283495345, 7.416198487095663, 7.483314773547883, 7.54983443527075, 7.615773105863909, 7.681145747868608, 7.745966692414834, 7.810249675906654, 7.874007874011811, 7.937253933193772, 8.0, 8.06225774829855, 8.12403840463596, 8.18535277187245, 8.246211251235321, 8.306623862918075, 8.366600265340756, 8.426149773176359, 8.48528137423857, 8.54400374531753, 8.602325267042627, 8.660254037844387, 8.717797887081348, 8.774964387392123, 8.831760866327848, 8.888194417315589, 8.94427190999916, 9.0, 9.055385138137417, 9.1104335791443, 9.16515138991168, 9.219544457292887, 9.273618495495704, 9.327379053088816, 9.38083151964686, 9.433981132056603, 9.486832980505138, 9.539392014169456, 9.591663046625438, 9.643650760992955, 9.695359714832659, 9.746794344808963, 9.797958971132712, 9.848857801796104, 9.899494936611665, 9.9498743710662, 10.0]
我只想打印完美的正方形。我需要在代码中添加什么内容?
答案 0 :(得分:1)
怎么样?:
[num for num in l if num == int(num)]
答案 1 :(得分:1)
由于简单的列表理解看起来很难看,我们可以定义像
这样的效用函数dotnet run
然后使用内置的filter
函数,如
import math
def is_perfect_square(number):
square_root = math.sqrt(number)
square_root_floor = int(square_root)
return square_root_floor * square_root_floor == number
perfect_squares = filter(is_perfect_square, range(101))
将是所需对象的list
,filter
上返回iterator,我们需要手动将其转换为perfect_squares
:
list
最后:
perfect_squares = list(filter(is_perfect_square, range(101)))
答案 2 :(得分:0)
为列表理解添加一个条件,制作一个衬垫(不先创建列表,然后再检查它)
l = [x for x in range(101) if int(x**0.5) == x**0.5]
答案 3 :(得分:0)
这也可以解决问题:
[x**0.5 for x in range(101) if x**0.5 % 1 == 0]
答案 4 :(得分:0)
我想要得到的输出是[0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
我特别想使用Lambda函数来做到这一点。我正在浏览旧文章进行改进,发现@Holle van提出了最佳答案,尽管我不喜欢这个int(x**0.5) == x**0.5
部分,所以结合了几个答案就提出了一个新的解决方案。
>>> [x for x in range(101) if x**0.5 % 1 == 0]
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100]