它可以使用常规循环工作,但我希望它可以使用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())
这就是我所拥有的:
result = { x = n, y = x**2 for n in range(1, 101)if n%x == 0 and y%3 == 0 }
答案 0 :(得分:0)
尝试
{(x, x**2) for x in range(1,101) if (x**2) %3 == 0}
答案 1 :(得分:0)
您可以凭一己之力list
理解这一点
result = {(n, n ** 2) for n in range(1, 101) if (n ** 2 % n) == 0 and ((n ** 2) % 3 == 0)}
但是,这样做的缺点是在综合期间必须计算n**2
三次。为了获得更好的性能,请生成两个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)}
后一个选项比前一个选项提供更好的性能
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