0

它使用常规循环工作,但我希望它使用集合理解工作。

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 }
4

2 回答 2

0

试试看

{(x, x**2) for x in range(1,101) if (x**2) %3 == 0}
于 2020-05-14T20:24:31.327 回答
0

您可以通过单行list理解来做到这一点

result = {(n, n ** 2) for n in range(1, 101) if (n ** 2 % n) == 0 and ((n ** 2) % 3 == 0)}

然而,这样做的缺点是n**2在综合过程中必须计算三次。为了获得更好的性能,生成两个listzip在理解中使用

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
于 2020-05-14T20:39:02.760 回答