我正在尝试学习python编程。 我尝试了以下代码,但它显示了以下错误。
就像你考虑一个数组Z = [1,2,3,4,5,6,7,8,9,10,11,12,13,14]
like output生成数组R = [[1,2,3,4], [2,3,4,5], [3,4,5,6], ..., [11,12,13,14]]
import numpy as np
Z = np.arange(1,15)
print(Z)
size = 4
step = 1
R = [Z[i : i + size] for i in range(0, len(Z), step)]
print(R)
rank = assert np.array_equal(R[1,:],np.array([2, 3, 4, 5]))
print(rank)
但是当检查np.array_equal
时,它会给我错误。
rank = assert np.array_equal(R [1,:],np.array([2,3,4,5])) ^ SyntaxError:语法无效
答案 0 :(得分:0)
我修复了创建语法,因此您只能获得大小为4的“切片”:
import numpy as np
Z = np.arange(1,15)
print(Z)
size = 4
step = 1
# Fixed: len(Z)-size not len(Z)
R = np.array( [Z[i : i + size] for i in range(0, len(Z)-size , step)] )
try:
assert R.shape == (len(Z)-size,size)
except ( AssertionError,IndexError ):
print(f'Error asserting: R.shape == ({len(Z)-size},{size})')
else: # print success message if assert is ok:
print(f'Asserted: R.shape == ({len(Z)-size},{size})')
这个断言将抛出:
try:
assert R.shape[1] == 99
except AssertionError :
print("Error asserting: assert R.shape[1] == 99")