整数平方根python列表

Mou*_*ott 0 python filter

有可能这是一个重复的问题,但我已经查看了重复的问题,我没有看到python的答案.

我正在尝试创建一个简单的程序,我可以硬编码整数列表并过滤掉所有具有整数平方根的数字.这是我到目前为止所拥有的:

# Python Program to display the number of integer square roots in a list
import math

# Change this list for testing
terms = [1,2,3,4,5,6,7,9,10,11,12,13,16,24,36]

all_roots = []  #list to hold all square roots from terms list

for i in terms:
    all_roots.append(math.sqrt(i))

#integer_roots = list(filter(lambda x: [????], all_roots)) #not sure what I should put in the "[????]" part

print(all_roots) #prints integer and floating square roots
print(integer_roots) #supposed to print only square roots that are integers
Run Code Online (Sandbox Code Playgroud)

澄清一下,print(all_roots)目前显示:

[1.0, 1.4142135623730951, 1.7320508075688772, 2.0, 2.23606797749979, 2.449489742783178, 2.6457513110645907, 3.0, 3.1622776601683795, 3.3166247903554, 3.4641016151377544, 3.605551275463989, 4.0, 4.898979485566356, 6.0]
Run Code Online (Sandbox Code Playgroud)

但我想print(integer_roots)展示

[1, 2, 3, 4, 6]
Run Code Online (Sandbox Code Playgroud)

Chr*_*nds 5

列表理解将有助于内部的生成器表达式,以防止重复的函数调用:

>>> [int(i) for i in (math.sqrt(i) for i in terms) if i.is_integer()]
[1, 2, 3, 4, 6]
Run Code Online (Sandbox Code Playgroud)

或者,如果您想要一种纯粹的功能性方法,因为您建议filter()在帖子中使用:

>>> list(map(int, filter(float.is_integer, map(math.sqrt, terms))))
[1, 2, 3, 4, 6]
Run Code Online (Sandbox Code Playgroud)

当然这可以用常规for循环写出来,这种循环性能较差但完全可以接受,特别是考虑到OP似乎是Python的新东西:

lst = []
for i in terms:
    s = math.sqrt(i)
    if s.is_integer():
         lst.append(int(s))
Run Code Online (Sandbox Code Playgroud)