毕达哥拉斯三胞胎使用python的列表理解

Ses*_*i R 1 list-comprehension pythagorean python-3.x

我可以使用for循环找出Pythagorean三元组,如下所示:

def triplet(n): # Find all the Pythagorean triplets between 1 and n (inclusive)
  for a in range(n+1):
    for b in range(a):
      for c in range(b):
        if a*a == b*b + c*c:
          print(a, b, c)
Run Code Online (Sandbox Code Playgroud)

我想使用list comprehension用一行代替它并尝试以下部分:

[a, b, c in range(n+1), range(a), range(b) if a*a == b*b + c*c]
Run Code Online (Sandbox Code Playgroud)

但是,我在结束方括号上得到语法错误.我试图使用简单的括号将列表更改为元组,但没有成功.我可以知道如何做对吗?

khe*_*ood 6

我想你的意思是

[(a,b,c) for a in range(n+1) for b in range(a) for c in range(b) if a*a == b*b + c*c]
Run Code Online (Sandbox Code Playgroud)

这至少在语法上是有效的.