我对python还是很陌生,我正设法避开下面的代码:
import numpy as np
n=4
matrix=np.zeros((n,n))
for j in range (0,n):
for i in range (n-1,n-j-2,-1):
matrix[i,j]=2*n-i-j-1
print (matrix)
如果有人可以帮助我理解每一行的执行方式以及如何通过循环重新评估代码,我将不胜感激。
谢谢!
答案 0 :(得分:2)
您可以添加以下print语句,循环将在每次迭代时对其进行解释:
n=4
matrix=np.zeros((n,n))
for i in range (0,n):
for j in range(0,i+1):
print(f'inserting {i-j+1} into the matrix at row index {i}, columns index {j}')
matrix[i,j]=i-j+1
运行它时,将得到以下输出:
inserting 1 into the matrix at row index 0, columns index 0
inserting 2 into the matrix at row index 1, columns index 0
inserting 1 into the matrix at row index 1, columns index 1
...
inserting 3 into the matrix at row index 3, columns index 1
inserting 2 into the matrix at row index 3, columns index 2
inserting 1 into the matrix at row index 3, columns index 3
然后像以前一样填充矩阵:
>>> matrix
array([[1., 0., 0., 0.],
[2., 1., 0., 0.],
[3., 2., 1., 0.],
[4., 3., 2., 1.]])
仅供参考:
>>> matrix
array([[1., 0., 0., 0.], #<- "row" index 0
[2., 1., 0., 0.], #<- "row" index 1
[3., 2., 1., 0.], #<- "row" index 2
[4., 3., 2., 1.]]) #<- "row" index 3
# ^ ... ^
# "col" 0 "col" 3
答案 1 :(得分:1)
var button: CustomButton!
var buttonSize: CGSize = CGSize(width: 0, height: 0)
override func performSetup(file: StaticString = #file, line: UInt = #line) {
super.performSetup(file: file, line: line)
autoreleasepool {
if button == nil {
button = CustomButton()
buttonSize = button.designDataMinimumButtonSize()
}
addToAndCenterWithinHostView(subview: button)
}
}
override func performTeardown(file: StaticString = #file, line: UInt = #line) {
// Verify that no strong reference cycles keep the test objects alive.
weak var weakComponent = button
autoreleasepool {
button.removeFromSuperview()
button = nil
super.performTeardown(file: file, line: line)
}
// This assertion tests for strong reference cycles in the tested code.
// However, if the assertion fails, it may be because the test did not
// wait for a closure that was asynchronously dispatched to finish. In
// that case, there is not a bug in the tested code and the test should
// be modified to wait for the dispatched closure to finish.
XCTAssertNil(weakComponent, "Expected no strong references to 'button' to exist.")
}
我们首先将所有坐标都设置为null的4x4矩阵进行设置:
import numpy as np
n=4
我们通过遍历行和列来设置新的坐标值。首先,我们遍历从索引0到n-1的行:
matrix=np.zeros((n,n))
我们接下来遍历各列。现在,请注意,我们仅遍历索引小于或等于当前行索引(即从0到i)的那些列。这样,我们可以确保设置的值在矩阵对角线上或下方:
for i in range (0,n):
最后,我们为当前坐标设置所需的值:
for j in range(0,i+1):