删除python numpy矩阵上的撇号

时间:2018-03-01 23:37:59

标签: python numpy matrix

我正在尝试用这段代码使用numpy在python 3上解决一个简单的矩阵问题:

import numpy

change_array = numpy.array(input().strip().split(' '))
change_array.shape = (3,3)

print(change_array)

此程序的输出带输入:  1 2 3 4 5 6 7 8 9

[['1' '2' '3']
 ['4' '5' '6']
 ['7' '8' '9']]

我希望输出没有这样的撇号:

[[1 2 3]
 [4 5 6]
 [7 8 9]]

但我还没有找到方法,任何帮助都会非常感激。

2 个答案:

答案 0 :(得分:1)

您必须将字符串转换为整数:

In [86]: x = np.array(input().strip().split())
1 2 3
In [87]: x
Out[87]: array(['1', '2', '3'], dtype='<U1')   # string dtype
In [88]: x.astype(int)
Out[88]: array([1, 2, 3])

In [89]: x = np.array(input().strip().split(), dtype=int)
4 5 6
In [90]: x
Out[90]: array([4, 5, 6])

或在列表级别进行转换

In [91]: x = [int(i) for i in input().strip().split()]
1 2 3
In [92]: x
Out[92]: [1, 2, 3]
In [93]: np.array(x)
Out[93]: array([1, 2, 3])

但要注意坏的价值

In [94]: x = np.array(input().strip().split(), dtype=int)
1 2 a
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-94-20cd8929f6ac> in <module>()
----> 1 x = np.array(input().strip().split(), dtype=int)

ValueError: invalid literal for int() with base 10: 'a'

答案 1 :(得分:0)

一种方法是使用import numpy as np from ast import literal_eval change_array = np.array(literal_eval(input())) # input: [[1, 2, 3], [4, 5, 6], [7, 8, 9]] change_array # array([[1, 2, 3], # [4, 5, 6], # [7, 8, 9]]) 。这需要输入一些额外的字符。但是,由于您在输入中定义了形状,因此它也更加明确。

openssl dgst -sha384 -binary FILENAME.js | openssl base64 -A