开发基础 size 大小
空值判断 strings, lists, tuples
1 2 3 4 5 6 7 if not seq:if seq:if len (seq):if not len (seq):
中断捕获 1 2 3 4 5 6 7 8 try : except Exception as e: pprint.pprint(list ) raise e finally : un_set()
for 间隔值 调参需要测试间隔值
1 2 for i in range (1 , 101 , 3 ): print (i)
遍历修改值
使用 enumerate 函数结合 for 循环遍历 list,以修改 list 中的元素。
enumerate 函数返回一个包含元组的迭代器,其中每个元组包含当前遍历元素的索引和值。在 for 循环中,我们通过索引 i 修改了列表中的元素。
1 2 3 4 5 baseline = appDataDict[0 ][0 ] for i, line in enumerate (appDataDict): for j, entry in enumerate (line): appDataDict[i][j] = round (entry/baseline, 7 )
itertools — 为高效循环而创建迭代器的函数
1 for a,b,c in permutations((a,b,c)):
小数位 x = round(x,3)# 保留小数点后三位
1 2 3 4 5 6 7 8 9 10 11 12 13 %c 格式化字符及其ASCII码 %s 格式化字符串 %d 格式化整数 %u 格式化无符号整型 %o 格式化无符号八进制数 %x 格式化无符号十六进制数 %X 格式化无符号十六进制数(大写) %f 格式化浮点数字,可指定小数点后的精度 %e 用科学计数法格式化浮点数 %E 作用同%e,用科学计数法格式化浮点数 %g %f和%e的简写 %G %F 和 %E 的简写 %p 用十六进制数格式化变量的地址
1 print ("My name is %s and weight is %d kg!" % ('Zara' , 21 ))
string <-> list ' '.join(pass_list) and pass_list.split(" ")
对齐"\n".join(["%-10s" % item for item in List_A])
开头判断 1 2 3 4 5 6 text = "Hello, world!" if text.startswith("Hello" ): print ("The string starts with 'Hello'" ) else : print ("The string does not start with 'Hello'" )
格式化 Python2.6 开始,通过 {} 和 : 来代替以前的 %
1 2 3 4 5 6 7 8 9 >>>"{} {}" .format ("hello" , "world" ) 'hello world' >>> "{1} {0} {1}" .format ("hello" , "world" ) 'world hello world' variable = "Hello" padded_variable = "{:<100}" .format (variable)
数字处理
1 2 3 4 print ("{:.2f}" .format (3.1415926 )) {:>10d} 右对齐 (默认, 宽度为10 ) {:^10d} 中间对齐 (宽度为10 )
NumPy
保留 frame_indices 中的值小于 max_frame 的元素。
1 frame_indices = frame_indices[frame_indices < max_frame]
容器:List https://www.runoob.com/python/python-lists.html
1 2 3 list = ['physics' , 'chemistry' , 1997 , 2000 ]list = [] print (list [0 ])
格式:[start_index:end_index:step]
不包括end_index的元素
1 2 3 4 5 6 7 8 list_three = [[0 for i in range (3 )] for j in range (3 )] //numpy 创建连续的,可自动向量化,线程并行 import numpy as npx3 = np.zeros((3 , 4 ), dtype=int ) x5 = np.full((3 , 4 ), 2 , dtype=int )
1 2 3 4 5 6 7 8 9 10 11 12 def takeSecond (elem ): return elem[2 ] LCData.sort(key=takeSecond)
1 2 3 tmp_list = [[],[],[],[]] [x.append(copy.deepcopy(entry)) for x,entry in zip (tmp_list, to_add)]
对于等长的
1 2 3 4 5 list1 = [1 , 2 , 3 , 4 , 5 ] list2 = [6 , 7 , 8 , 9 , 10 ] result = [x + y for x, y in zip (list1, list2)] print (result)
如果两个列表的长度不同,你可以使用zip_longest()函数来处理它们。zip_longest()函数可以处理不等长的列表,并使用指定的填充值填充缺失的元素。
1 2 3 4 5 6 7 from itertools import zip_longestlist1 = [1 , 2 , 3 , 4 , 5 ] list2 = [6 , 7 , 8 ] result = [x + y for x, y in zip_longest(list1, list2, fillvalue=0 )] print (result)
如果是二维list
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 list1 = [[1 , 2 , 3 ], [4 , 5 , 6 ], [7 , 8 , 9 ]] list2 = [[10 , 11 , 12 ], [13 , 14 , 15 ]] rows = max (len (list1), len (list2)) cols = max (len (row) for row in list1 + list2) result = [[0 ] * cols for _ in range (rows)] for i in range (rows): for j in range (cols): if i < len (list1) and j < len (list1[i]): result[i][j] += list1[i][j] if i < len (list2) and j < len (list2[i]): result[i][j] += list2[i][j] print (result)result = [[element / A for element in row] for row in list1]
容器:元组Tuple
元组和列表类似,但是不同的是元组不能修改 ,但可以对元组进行连接组合,元组使用小括号。
元组中只包含一个元素时,需要在元素后面添加逗号 ,否则括号会被当作运算符使用。
1 2 3 4 5 tup = (1 , 2 , 3 , 4 , 5 ) tup1 = (23 , 78 ); tup2 = ('ab' , 'cd' ) tup3 = tup1 + tup2
容器:Dict 初始化 1 2 3 >>> tinydict = {'a' : 1 , 'b' : 2 , 'b' : '3' }>>> tinydict['b' ]'3'
empty dict
1 2 3 4 5 6 7 8 9 10 11 12 13 a_dict = {'color' : 'blue' } for key in a_dict: print (key) for key in a_dict: print (key, '->' , a_dict[key]) for item in a_dict.items(): print (item) for key, value in a_dict.items(): print (key, '->' , value)
类似c++ 的 pair<int,int>
1 2 3 4 5 6 7 8 9 10 11 class RoPE3D (nn.Module): def __init__ (self, freq=10000.0 , interpolation_scale=(1 , 1 , 1 ) ): super ().__init__() self .cache = {} def get_cos_sin (self, dim, seq_len, device, dtype, interpolation_scale=1 ): if (dim, seq_len, device, dtype) not in self .cache: self .cache[dim, seq_len, device, dtype] = (cos, sin) return self .cache[dim, seq_len, device, dtype]
关于 if (dim, seq_len, device, dtype) not in self.cache 的条件判断
这里检查的是 整个元组作为字典的键 是否存在,而不是检查单个元素。
例如:字典 self.cache 的键是类似 (128, 100, "cuda", torch.float32) 的元组。
当且仅当 (dim, seq_len, device, dtype) 这个完整元组不在字典中时,条件为 True,才会执行后续代码。
如果元组中的任意一个元素不同(如 seq_len 变化),则会被视为不同的键。
关于 self.cache[...] = (cos, sin) 的赋值
这是一个 将元组作为键,元组作为值 的字典设计。
键是 (dim, seq_len, device, dtype) 的四元组,用于唯一标识一组计算参数。
值是对应的 (cos值张量, sin值张量) 的二元组,因为这两个张量总是成对出现。
例如:self.cache[(128, 100, "cuda", float32)] = (cos_tensor, sin_tensor)
进一步解释这种设计的目的 :
缓存机制 :避免重复计算相同参数的 cos/sin,不同参数组合会生成不同的键。
元组作为键的合法性 :Python允许用不可变类型(如元组)作为字典键。
高效查询 :通过参数元组直接定位到预计算结果,提升性能。
你可以通过一个简单例子验证:
1 2 3 4 5 6 cache = {} key = (128 , 100 , "cuda" , "float32" ) cache[key] = ("cos" , "sin" ) print ( (128 , 100 , "cuda" , "float32" ) in cache ) print ( (128 , 200 , "cuda" , "float32" ) in cache )
1 bblHashDict[(tmpHigherHash,tmpLowerHash)]=tmpBBL
但是这样就不支持json.dump, json.dump() 无法序列化 Python 中元组(tuple)作为字典的 key,这会导致 json.dump() 函数在写入此类字典数据时会进入死循环或陷入卡住状态
删 1 2 3 del tinydict['Name' ] tinydict.clear() del tinydict
改 1 2 3 4 tinydict = {'Name' : 'Zara' , 'Age' : 7 , 'Class' : 'First' } tinydict['Age' ] = 8 tinydict['School' ] = "RUNOOB"
1 2 3 4 5 6 7 dict1 = {'a' : 10 , 'b' : 8 } dict2 = {'d' : 6 , 'c' : 4 } dict2.update(dict1) print (dict2){'d' : 6 , 'c' : 4 , 'a' : 10 , 'b' : 8 }
查
以下是两种常用的方法:
方法一:使用in操作符: in操作符返回一个布尔值,True表示存在,False表示不存在。
1 2 3 4 5 6 7 8 Copy code my_dict = {"key1" : "value1" , "key2" : "value2" , "key3" : "value3" } if "key2" in my_dict: print ("Key 'key2' exists in the dictionary." ) else : print ("Key 'key2' does not exist in the dictionary." )
方法二:使用dict.get()方法: dict.get()方法在键存在时返回对应的值,不存在时返回None。根据需要选择适合的方法进行判断。
1 2 3 4 5 6 7 8 Copy code my_dict = {"key1" : "value1" , "key2" : "value2" , "key3" : "value3" } if my_dict.get("key2" ) is not None : print ("Key 'key2' exists in the dictionary." ) else : print ("Key 'key2' does not exist in the dictionary." )
这两种方法都可以用来判断字典中是否存在指定的键。
容器:set 无序不重复序列
初始化 1 2 3 4 5 a= set () thisset = set (("Google" , "Runoob" , "Taobao" )) >>> basket = {'apple' , 'orange' , 'apple' , 'pear' , 'orange' , 'banana' }>>> print (basket)
增
删 1 2 3 4 s.remove( x ) my_set.discard(3 ) a.clear()
改
1 2 3 4 5 6 7 x = {"apple" , "banana" , "cherry" } y = {"google" , "runoob" , "apple" } z = x.union(y) print (z)
类型转换 list2set
set2list 1 2 3 4 5 my_set = {'Geeks' , 'for' , 'geeks' } s = list (my_set) print (s)
参考文献 https://blog.csdn.net/weixin_63719049/article/details/125680242