要想代码写的顺手, l i s t 、 n u m p y 、 t e n s o r 的操作一定要烂熟于心 要想代码写的顺手,list、numpy、tensor的操作一定要烂熟于心 要想代码写的顺手,list、numpy、tensor的操作一定要烂熟于心
一、list列表
1.1 list创建
list 是Python中最基本的数据结构。序列中的每个元素都分配一个数字(它的位置index),与字符串的索引一样,列表索引从0开始。列表可以进行索引,切片,加,乘,检查成员,截取、组合等。在[]内用逗号分隔开任意类型的值,可以实现索引存取。
- 直接创建 :
l = [1,2,3,4,5]
l[0] = 10
print(l[0])
10
- 列表生成式:
l = [e for e in range(10)]
print(l)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
1.1 list内置方法
- 切片[start (开始),stop (停止),step(步长)]:列表切片的方向取决于起始索引、结束索引以及步长,当起始索引在结束索引右边是就是从右往左取值,同理反之。
当步长为负数时
,从start开始索引至stop
,起点必须大于终点。
a[:] # a copy of the whole array
a[start:] # items start through the rest of the array
a[:stop] # items from the beginning through stop-1
a[start:stop] # items start through stop-1
a[start:stop:step] # start through not past stop, by stepa[-1] # last item in the array
a[-2:] # last two items in the array
a[:-2] # every items except the last two itemsa[::-1] # all items in the array, reversed
a[1::-1] # the first two items, reversed
a[:-3:-1] # the last two items, reversed
a[-3::-1] # every items except the last two items, reversed
- 索引存取[idx]:
正向取值+反向取值
,即可存也可以取list[idx]
。
L = ['Google', 'Runoob', 'Taobao']
print(L[0], L[-1]) # 读取列表第一个和倒数第一个元素
Google Taobao
- 拼接+:
+号
用于拼接列表。
l = [1,2,3] + [4,5,6]
print(l)
[1, 2, 3, 4, 5, 6]
- 重复* :
*号
用于重复列表。
l2 = [1]*5
print(l2)
[1, 1, 1, 1, 1]
- 长度len():列表元素个数
len(list)
l = [1,2,3,4,5,6]
print(len(l))
- 成员运算in和not in:判断某元素十否在list中,
e in list
l = [1,2,3,4,5,6]
print(3 in l)
print(6 not in l)
True
False
- 按下标删除del:按照下标idx 使用 del 语句来删除列表的元素,
del list[idx]
l = [1,2,3,4,5,6]
del l[0]
print(l)
[2, 3, 4, 5, 6]
- 插入insert():对任意位置idx插入元素
list.insert(idx,e)
l = [1,2,4]
l.insert(2,3)
print(l)
[1, 2, 3, 4]
- 追加值append():在列表末尾添加新的对象,
list.append(e)
l = [1,2,3,4,5,6]
l.append(7)
print(l)
[1, 2, 3, 4, 5, 6, 7]
- 弹栈pop():
list.pop()
默认删除最后一个元素
l = [1,2,3,4]
l.pop()
print(l)
[1, 2, 3]
- 按值删除remove():从左向右顺序遍历,删除第一个找到的对应值的元素
list.remove(e)
l = [1,2,3,3,3]
l.remove(3)
print(l)
[1, 2, 3, 3]
- 清空clear():清空list内所有元素,
list.clear()
l = [1,2,3,3,3]
l.clear()
print(l)
[]
- 反转reverse():反转列表
list.reverse()
l = [1,2,3,4,5]
l.reverse()
print(l)
[5, 4, 3, 2, 1]
- 排序sort():可以降序或升序排序,
list.sort(reverse=Ture/False)
l = [1,2,3,4,5]
l.sort(reverse=True)
print(l)
[5, 4, 3, 2, 1]
- 查找index():查找对应元素的下标(顺序查找第一个),
list.index(e)
l = [1,2,3,3,3]
print(l.index(3))
2
- 统计个数count():统计对应元素出现次数
list.count(e)
l = [1,2,3,3,3]
print(l.count(3))
3
二、numpy矩阵
2.1 创建numpy.ndarray
NumPy 最重要的一个特点是其 N 维数组对象 ndarray,它是一系列同类型数据的集合,以 0 下标为开始进行集合中元素的索引。
- 直接创建numpy.array():
object
是list对象,dtype
(可选)数组元素的数据类,copy
(可选)对象是否需要复制,order
(默认A)创建数组的样式,C为行方向,F为列方向,A为任意方向,subok
默认返回一个与基类类型一致的数组,ndmin
指定生成数组的最小维度
numpy.array(object, dtype = None, copy = True, order = None, subok = False, ndmin = 0)
n = np.array([[1,2,3],[4,5,6]])
print(n)
[[1 2 3]
[4 5 6]]