1. 程式人生 > >numpy array和 list 的相互轉化,和 [np.where(x == i)[0] for i in range(10)] 的意思

numpy array和 list 的相互轉化,和 [np.where(x == i)[0] for i in range(10)] 的意思

1.list 轉 numpy array
a = [0,2,3,2,1,2,4,5,6,7,8,6,5,4,3,2,7,8,9,6,5,7,8,9,6,9,1,2,2,5,6,8,8,9,7,0]
x = np.array(a)
print(x)

 2. numpy array 轉 list

a = [0,2,3,2,1,2,4,5,6,7,8,6,5,4,3,2,7,8,9,6,5,7,8,9,6,9,1,2,2,5,6,8,8,9,7,0]
    x = np.array(a)

x.tolist()

3.其他用法:

a = [0,2,3,2,1,2,4,5,6,7,8,6,5,4,3,2,7,8,9,6,5,7,8,9,6,9,1,2,2,5,6,8,8,9,7,0]
x = np.array(a)
# print(x)
# print(x[1])
print(np.where(x>=5))  #輸出的型別是一個元組,元組的第一個元素是list
print(np.where(x>=5)[0]) #輸出的型別是list
print('type np.where(x>=5):', type(np.where(x>=5)))
print('type np.where(x>=5)[0]:', type(np.where(x>=5)[0]))
digit_indices = [np.where(x == i)[0] for i in range(10)] #輸出的是一個list,list裡每個元素都是元組,元組裡的第一個元素是list,具體看下面輸出
print('digit_indices:', type(digit_indices))
print('digit_indices:', digit_indices)

 輸出:

(array([ 7,  8,  9, 10, 11, 12, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 29,
       30, 31, 32, 33, 34], dtype=int64),)
[ 7  8  9 10 11 12 16 17 18 19 20 21 22 23 24 25 29 30 31 32 33 34]
type np.where(x>=5): <class 'tuple'>
type np.where(x>=5)[0]: <class 'numpy.ndarray'>
digit_indices: <class 'list'>
digit_indices: [array([ 0, 35], dtype=int64), array([ 4, 26], dtype=int64), array([ 1,  3,  5, 15, 27, 28], dtype=int64), array([ 2, 14], dtype=int64), array([ 6, 13], dtype=int64), array([ 7, 12, 20, 29], dtype=int64), array([ 8, 11, 19, 24, 30], dtype=int64), array([ 9, 16, 21, 34], dtype=int64), array([10, 17, 22, 31, 32], dtype=int64), array([18, 23, 25, 33], dtype=int64)]