【Python】知识点零碎学习3

defaultdict

defaultdict(list),会构建一个默认value为list的字典;

该值将用作字典中不存在的键的默认值

python 复制代码
d = defaultdict(list)  # 如果 key 不在字典中,则自动插入一个空列表
for s in strs:
   sorted_s = ''.join(sorted(s))  # 把 s 排序,作为哈希表的 key
   d[sorted_s].append(s)  # 排序后相同的字符串分到同一组
return list(d.values())  # 哈希表的 value 保存分组后的结果

combinations

全组合函数combinations(iterable, r):返回iterable中所有长度为r的子序列,返回的子序列中的项按输入iterable中的顺序排序。

python 复制代码
from itertools import combinations
a=[1,2,3]
list(combinations(a,2))#[(1,2),(1,3),(2,3)]

torch.full

torch.full(size,full_value):生成一个size大小的,每一个值都是full_value的张量

python 复制代码
torch.full((2, 3), 3.141592)

#tensor([[ 3.1416,  3.1416,  3.1416],
#        [ 3.1416,  3.1416,  3.1416]])

torch.mean

torch.mean(input):返回input中所有元素的平均值;input要求浮点型或者复数型

torch.mean(input, dim, keep_dim=False):

dim:在dim这个维度上返回input的平均值;如果dim是一个列表,要求所有这些维度进行规约。

keep_dim默认为False,此时输出张量维度减少len(dim)个;当为True时,输出张量大小与input相同,在dim的维度上为1。

python 复制代码
a = torch.randn(4, 4)
#tensor([[-0.3841,  0.6320,  0.4254, -0.7384],
#        [-0.9644,  1.0131, -0.6549, -1.4279],
#        [-0.2951, -1.3350, -0.7694,  0.5600],
#        [ 1.0842, -0.9580,  0.3623,  0.2343]])
torch.mean(a, 1)
#tensor([-0.0163, -0.5085, -0.4599,  0.1807])
torch.mean(a, 1, True)
#tensor([[-0.0163],
#        [-0.5085],
#        [-0.4599],
#        [ 0.1807]])

rearrange

rearrange(input, pattern: str, **axes_lengths):重排张量维度,进行维度变换

input:输入张量

pattern:调整规则

axes_lengths:附加的尺寸规格

python 复制代码
images = torch.randn((32,30,40,3))

print(rearrange(images, 'b h w c -> h (b w) c').shape)# (30, 1280, 3)

print(rearrange(images, 'b (h h1) (w w1) c -> (b h1 w1) h w c', h1=2, w1=2).shape)# (128, 15, 20, 3)

torch.clamp

torch,clamp(input, min, max):将input中的元素都限制在[min,max]之间;若min为none,则没有下界;若max为none,则没有上界。

即y=min(max, max(input,min))

python 复制代码
a = torch.randn(4)
#tensor([-1.7120,  0.1734, -0.0478, -0.0922])
torch.clamp(a, min=-0.5, max=0.5)
#tensor([-0.5000,  0.1734, -0.0478, -0.0922])

相关推荐
玄同76521 小时前
LangChain 1.0 模型接口:多厂商集成与统一调用
开发语言·人工智能·python·langchain·知识图谱·rag·智能体
特立独行的猫a1 天前
C++轻量级Web框架介绍与对比:Crow与httplib
开发语言·前端·c++·crow·httplib
fie88891 天前
基于C#的推箱子小游戏实现
开发语言·c#
EnglishJun1 天前
数据结构的学习(四)---栈和队列
数据结构·学习
喵手1 天前
Python爬虫实战:构建招聘会数据采集系统 - requests+lxml 实战企业名单爬取与智能分析!
爬虫·python·爬虫实战·requests·lxml·零基础python爬虫教学·招聘会数据采集
菜鸟小芯1 天前
Qt Creator 集成开发环境下载安装
开发语言·qt
阿猿收手吧!1 天前
【C++】引用类型全解析:左值、右值与万能引用
开发语言·c++
「QT(C++)开发工程师」1 天前
C++ 策略模式
开发语言·c++·策略模式
专注VB编程开发20年1 天前
python图片验证码识别selenium爬虫--超级鹰实现自动登录,滑块,点击
数据库·python·mysql
2501_901147831 天前
学习笔记:单调递增数字求解的迭代优化与工程实践
linux·服务器·笔记·学习·算法