如何使用列表解析来打印python中长方体的所有可能维度的列表?

ia2d9nvy  于 2023-05-27  发布在  Python
关注(0)|答案(5)|浏览(165)

你有三个整数x,y和z,代表长方体的尺寸沿着还有一个整数n。在三维网格上打印由(i,j,k)给出的所有可能的坐标列表,其中i+j+k的和不等于n。这里,0<=i<=x; 0<=j<=y;0<=k<=z。请使用列表解析而不是多个循环,作为学习练习。
我不能解决这个问题。有人能帮我吗?

vulvrdjw

vulvrdjw1#

ifname== 'main':

x=int(input())
y=int(input())
z=int(input())
n=int(input())
ans[]
for i in range(x+1):
  for j in range(y+1):
    for k in range(z+1):

       if(i+j+k)!=n:
          ans.append([i,j,k])

print(ans)
prdp8dxp

prdp8dxp2#

在线试试!

x, y, z, n = 2, 3, 4, 5
print([(i, j, k) for i in range(x + 1) for j in range(y + 1)
    for k in range(z + 1) if i + j + k != n])

输出:

[(0, 0, 0), (0, 0, 1), (0, 0, 2), (0, 0, 3), (0, 0, 4), (0, 1, 0), (0, 1, 1), (0, 1, 2), (0, 1, 3), (0, 2, 0), (0, 2, 1), (0, 2, 2), (0, 2, 4), (0, 3, 0), (0, 3, 1), (0, 3, 3), (0, 3, 4), (1, 0, 0), (1, 0, 1), (1, 0, 2), (1, 0, 3), (1, 1, 0), (1, 1, 1), (1, 1, 2), (1, 1, 4), (1, 2, 0), (1, 2, 1), (1, 2, 3), (1, 2, 4), (1, 3, 0), (1, 3, 2), (1, 3, 3), (1, 3, 4), (2, 0, 0), (2, 0, 1), (2, 0, 2), (2, 0, 4), (2, 1, 0), (2, 1, 1), (2, 1, 3), (2, 1, 4), (2, 2, 0), (2, 2, 2), (2, 2, 3), (2, 2, 4), (2, 3, 1), (2, 3, 2), (2, 3, 3), (2, 3, 4)]
pn9klfpd

pn9klfpd3#

if __name__ == '__main__':
    x, y, z, n = (int(input().strip()) for _ in range(4))
    print([[i,j,k] for i in range(x+1) for j in range(y+1) for k in range(z+1) if i+j+k!=n ])
prdp8dxp

prdp8dxp4#

print([[a, b, c] for a in range(x + 1) for b in range(y + 1) for c in range(z + 1) if a + b + c != n])
umuewwlo

umuewwlo5#

如果你的目标是打印一个列表列表所有可能的组合(i,j,k)对于给定的x,y,z值,其中i + j + k的总和不等于n,你可以尝试:

print([[i, j, k] for i in range(x + 1) for j in range(y + 1)
    for k in range(z + 1) if i + j + k != n])

相关问题