我正在尝试将此for循环转换为列表理解:
a = [1,2,3,4,5,6,7,8,9]
result = []
for i in a:
if i <= 3:
result.append(1)
elif i > 4 and i < 7:
result.append(2)
Run Code Online (Sandbox Code Playgroud)
我已经尝试过了
[1 if i <= 3 else 2 if i > 3 and i < 7 for i in a]
Run Code Online (Sandbox Code Playgroud)
抱怨
File "<ipython-input-155-eebf07a9e0d8>", line 2
[1 if i <= 3 else 2 if i > 3 and i < 7 for i in a]
^
SyntaxError: invalid syntax
Run Code Online (Sandbox Code Playgroud) 我试图用整数填充数组,但似乎numpy数组继续将整数转换为浮点数.为什么会发生这种情况?如何阻止这种情况?
arr = np.empty(9)
arr[3] = 7
print(arr[3])
>>>7.0
Run Code Online (Sandbox Code Playgroud)