微网站开发商,网站建成,网站开发文档网站,wordpress页面发布失败要想代码写的顺手#xff0c; l i s t 、 n u m p y 、 t e n s o r 的操作一定要烂熟于心 要想代码写的顺手#xff0c;list、numpy、tensor的操作一定要烂熟于心 要想代码写的顺手#xff0c;list、numpy、tensor的操作一定要烂熟于心
一、list列表
1.1 list创建
list … 要想代码写的顺手 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(reverseTure/False)
l [1,2,3,4,5]
l.sort(reverseTrue)
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]]