这可能是一个重复的问题,但我已经查看了重复的问题,我没有看到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
为了澄清,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]
但我希望print(integer_roots)
显示
[1, 2, 3, 4, 6]
答案 0 :(得分:5)
列表解析有助于在内部生成表达式以防止重复的函数调用:
>>> [int(i) for i in (math.sqrt(i) for i in terms) if i.is_integer()]
[1, 2, 3, 4, 6]
或者,如果您想要一种纯粹的功能性方法,因为您建议在帖子中使用filter()
:
>>> list(map(int, filter(float.is_integer, map(math.sqrt, terms))))
[1, 2, 3, 4, 6]
当然这可以用常规for
循环写出来,这个循环性能较差但完全可以接受,特别是考虑到OP似乎是Python的新东西:
lst = []
for i in terms:
s = math.sqrt(i)
if s.is_integer():
lst.append(int(s))
答案 1 :(得分:2)
import math
terms = [1,2,3,4,5,6,7,9,10,11,12,13,16,24,36]
integer_roots = []
for i in terms:
tmp = math.sqrt(i)
if (tmp.is_integer()):
integer_roots.append(int(tmp))
print(integer_roots)