[英]List Comprehensions and Loops
I'm currently going through different Python3 challenges on Hackerrank and I ran into this problem that caught me off guard. 我目前在Hackerrank上经历了不同的Python3挑战,遇到了这个使我措手不及的问题。 I found the solution but I'm having trouble wrapping my mind around how it works.
我找到了解决方案,但我无法确定如何解决问题。 I'm familiar with loops in python but I can't seem to trace the code step by step.
我熟悉python中的循环,但是我似乎无法逐步跟踪代码。
You are given three integers X, Y, and Z representing the dimensions of a cuboid along with an integer N . 您将获得三个整数X,Y和Z以及一个整数N ,它们分别表示一个长方体的尺寸。 You have to print a list of all possible coordinates given by on a 3D grid where the sum of is not equal to N .
您必须在3D网格上打印出的所有可能坐标的列表,其中的总和不等于N。
Four integers X, Y, Z, and N each on four separate lines, respectively. 四个整数X,Y,Z和N分别位于四行中。
Print the list in lexicographic increasing order. 按字典顺序升序打印列表。
1
1
1
2
[[0, 0, 0], [0, 0, 1], [0, 1, 0], [1, 0, 0], [1, 1, 1]]
x, y, z, n = (int(input()) for _ in range(4))
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])
Let's think about how list comprehensions work. 让我们考虑一下列表推导如何工作。
The list comprehension you've posted works like the following loops: 您发布的列表理解类似于以下循环:
l = []
for a in range(x):
for b in range(y):
for c in range(z):
if a+b+c!= n:
l.append([a,b,c])
print(l)
So, we loop across all possible values of a , b ,and c , and find the triplets that satisfy our condition. 因此,我们遍历a , b和c的所有可能值,并找到满足我们条件的三元组。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.