mirror of
https://github.com/apachecn/ailearning.git
synced 2026-02-11 14:26:04 +08:00
100 lines
1.0 KiB
Markdown
100 lines
1.0 KiB
Markdown
# 数组与字符串的转换
|
||
|
||
## tostring 方法
|
||
|
||
In [1]:
|
||
|
||
```py
|
||
import numpy as np
|
||
|
||
```
|
||
|
||
In [2]:
|
||
|
||
```py
|
||
a = np.array([[1,2],
|
||
[3,4]],
|
||
dtype = np.uint8)
|
||
|
||
```
|
||
|
||
转化为字符串:
|
||
|
||
In [3]:
|
||
|
||
```py
|
||
a.tostring()
|
||
|
||
```
|
||
|
||
Out[3]:
|
||
|
||
```py
|
||
'\x01\x02\x03\x04'
|
||
```
|
||
|
||
我们可以使用不同的顺序来转换字符串:
|
||
|
||
In [4]:
|
||
|
||
```py
|
||
a.tostring(order='F')
|
||
|
||
```
|
||
|
||
Out[4]:
|
||
|
||
```py
|
||
'\x01\x03\x02\x04'
|
||
```
|
||
|
||
这里使用了**Fortran**的格式,按照列来读数据。
|
||
|
||
## fromstring 函数
|
||
|
||
可以使用 `fromstring` 函数从字符串中读出数据,不过要指定类型:
|
||
|
||
In [5]:
|
||
|
||
```py
|
||
s = a.tostring()
|
||
a = np.fromstring(s,
|
||
dtype=np.uint8)
|
||
a
|
||
|
||
```
|
||
|
||
Out[5]:
|
||
|
||
```py
|
||
array([1, 2, 3, 4], dtype=uint8)
|
||
```
|
||
|
||
此时,返回的数组是一维的,需要重新设定维度:
|
||
|
||
In [6]:
|
||
|
||
```py
|
||
a.shape = 2,2
|
||
a
|
||
|
||
```
|
||
|
||
Out[6]:
|
||
|
||
```py
|
||
array([[1, 2],
|
||
[3, 4]], dtype=uint8)
|
||
```
|
||
|
||
对于文本文件,推荐使用
|
||
|
||
* `loadtxt`
|
||
* `genfromtxt`
|
||
* `savetxt`
|
||
|
||
对于二进制文本文件,推荐使用
|
||
|
||
* `save`
|
||
* `load`
|
||
* `savez` |