[英]How would I write this using set comprehension?
It works using a regular loop but I want it to work using set comprehension.它使用常规循环工作,但我希望它使用集合理解工作。
def setComp():
result = set()
for n in range(1, 101):
x = n
y = x**2
if y%x == 0 and y%3 == 0:
tup = (x,y)
result.add(tup)
return result
print(setComp())
This is what I have:这就是我所拥有的:
result = { x = n, y = x**2 for n in range(1, 101)if n%x == 0 and y%3 == 0 }
Try it试试看
{(x, x**2) for x in range(1,101) if (x**2) %3 == 0}
You can do this with a one-liner list
comprehension您可以使用单行
list
理解来做到这一点
result = {(n, n ** 2) for n in range(1, 101) if (n ** 2 % n) == 0 and ((n ** 2) % 3 == 0)}
However the downside to this is that is has to calculate n**2
three times during the comprehensive.然而,这样做的缺点是在综合过程中必须计算
n**2
三次。 For better performance, generate two list
and use zip
in the comprehension为了获得更好的性能,生成两个
list
并在理解中使用zip
xs = range(1, 101)
ys = [n ** 2 for n in q]
reuslts = {(x, y) for x, y in zip(xs, ys) if (y % x) == 0 and (y % 3 == 0)}
The latter option provides better performance than the former后一个选项比前一个选项提供更好的性能
import timeit
xs = range(1, 101)
ys = [n ** 2 for n in xs]
def l():
return {(n, n ** 2) for n in xs if (n ** 2 % n) == 0 and ((n ** 2) % 3 == 0)}
def f():
return {(x, y) for x, y in zip(xs, ys) if (y % x) == 0 and (y % 3 == 0)}
print('l', timeit.timeit(l))
>>> 68.20
print('f', timeit.timeit(f))
>>> 19.67
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.