【python入门】数组,列表

1.axis(轴)

import numpy as np

ndarray = np.arange(1,10).reshape(3,3)

a = ndarray.sum()
b = ndarray.sum(axis = 1)  #分别计算每一列的和
c = ndarray.sum(axis = 0)  #分别计算每一行的和
d = ndarray[:][0:2]        #轴0全部都取,轴1从0开始,只取2列

print('a---',a)
print('b---',b)
print('c---',c)
print('------------------')
print(d)
#输出
#a--- 45
#b--- [ 6 15 24]
#c--- [12 15 18]
#------------------
#[1 2 3]
#[4 5 6]]

2.append 用法

示例:

mylist = [1,2,0,’abc’]
mylist
[1, 2, 0, ‘abc’]
mylist.append(4)
mylist
[1, 2, 0, ‘abc’, 4]
mylist.append(‘haha’)
mylist
[1, 2, 0, ‘abc’, 4, ‘haha’]
注意:使用完append()函数以后的新的列表

weibo=[]
wei=[1,23,34,5,6,6,6,624,624,32,534,352,2352,2525,2152]
weibo.append(wei)
print weibo
# 返回结果:[[1, 23, 34, 5, 6, 6, 6, 624, 624, 32, 534, 352, 2352, 2525, 2152]]
print type(weibo)
# 返回结果:<type 'list'>
# 若此时要判断wei列表与weibo列表是否相同我们如果使用isinstance函数就会出现错误
print isinstance(weibo,wei)
# 返回结果:TypeError: isinstance() arg 2 must be a class, type, or tuple of classes and types
# 因为isinstance()比较必须是一个类,类型,或元组的类和类型 

# 在python还有一个相似的extend()其只能对列表进行黏贴。

3.Shape

因为实际应用的时候可能会有很多维度,所以这个函数是用来解析维度的.有一个很详细的博客.

import numpy as np
a = np.array([[2,8],[6,8],[9,4],[5,3]])
c = a.shape[0]      #4print(c)            
print(a.shape[1])   #2print(a[c-1,0])#数组的取数运算,即a[c-1][0]
print(a[c-1,1])

#python numpyy.py
#output
#4
#2
#5
#3
# 有时候会看到参数是这样的结构(2,):表示这是一维数组
b = np.array([1,2,5,6])
print(b.shape)
d = np.array([[[4,5,6]]])
print(d.shape)
e = np.array([[[1,2,3],[4,5,6]]])
print(e.shape)
#output
#(4,)
#(1,1,3)
#(1,2,3)

猜你喜欢

转载自blog.csdn.net/acbattle/article/details/80580505