# NumPy - 來自現有資料的陣列

## `numpy.asarray`

``````numpy.asarray(a, dtype = None, order = None)
``````

1. `a` 任意形式的輸入引數，比如列表、列表的元組、元組、元組的元組、元組的列表
2. `dtype` 通常，輸入資料的型別會應用到返回的`ndarray`
3. `order` `'C'`為按行的 C 風格陣列，`'F'`為按列的 Fortran 風格陣列

### 範例 1

``````# 將列表轉換為 ndarray
import numpy as np

x =  [1,2,3]
a = np.asarray(x)
print a
``````

``````[1  2  3]
``````

### 範例 2

``````# 設定了 dtype
import numpy as np

x =  [1,2,3]
a = np.asarray(x, dtype =  float)
print a
``````

``````[ 1.  2.  3.]
``````

### 範例 3

``````# 來自元組的 ndarray
import numpy as np

x =  (1,2,3)
a = np.asarray(x)
print a
``````

``````[1  2  3]
``````

### 範例 4

``````# 來自元組列表的 ndarray
import numpy as np

x =  [(1,2,3),(4,5)]
a = np.asarray(x)
print a
``````

``````[(1, 2, 3) (4, 5)]
``````

## `numpy.frombuffer`

``````numpy.frombuffer(buffer, dtype = float, count = -1, offset = 0)
``````

1. `buffer` 任何暴露緩衝區藉口的物件
2. `dtype` 返回陣列的資料型別，預設為`float`
3. `count` 需要讀取的資料數量，預設為`-1`，讀取所有資料
4. `offset` 需要讀取的起始位置，預設為`0`

### 範例

``````import numpy as np
s =  'Hello World'
a = np.frombuffer(s, dtype =  'S1')
print a
``````

``````['H'  'e'  'l'  'l'  'o'  ' '  'W'  'o'  'r'  'l'  'd']
``````

## `numpy.fromiter`

``````numpy.fromiter(iterable, dtype, count = -1)
``````

1. `iterable` 任何可疊代物件
2. `dtype` 返回陣列的資料型別
3. `count` 需要讀取的資料數量，預設為`-1`，讀取所有資料

### 範例 1

``````# 使用 range 函式建立列表物件
import numpy as np
list = range(5)
print list
``````

``````[0,  1,  2,  3,  4]
``````

### 範例 2

``````# 從列表中獲得疊代器
import numpy as np
list = range(5)
it = iter(list)
# 使用疊代器建立 ndarray
x = np.fromiter(it, dtype =  float)
print x
``````

``````[0.   1.   2.   3.   4.]
``````