python笔记
int():
浮点数转int或整数字符串转int,int(‘1’) = int(1.2) = 1
join:
'.'.join(['abc','def']):'abc.def'
字典排序:
dic = {'a':2,'b':1}
按key降序:
a = sorted(dic.items(),key=lambda d:d[0],reverse=True)
[('b', 1), ('a', 2)]
按value升序:
b = sorted(dic.items(),key=lambda d:d[1])
[('b', 1), ('a', 2)]
sorted(“123321”)返回[‘1’, ‘1’, ‘2’, ‘2’, ‘3’, ‘3’]
整数转字符串:str_int = '%02d' % i
list排序:
def takeSecond(elem):
return elem[1]
acc_list.sort(key=takeSecond) # reverse=True
list交集、并集、差集:
交集:list(set(a).intersection(set(b)))
并集:list(set(a).union(set(b)))
差集:list(set(a).difference(set(b))) # a有b没有
list最大、最小值索引:
a_list.index(max(a_list))
多list组合:
iter = zip(list1,list2,list3)
list_merge = list(iter)
例子:
list拆分:
big_list = [i for i in range(100)]
devide_list = [big_list [i:i+N] for i in range(0, len(big_list ), N)]
list合并:
merge_list = []
[merge_list .extend(sub) for sub in devide_list]
list生成:
a = np.arange(0,10,2)
print(list(a)) # [0, 2, 4, 6, 8]
list对应元素运算:
v1 = [21, 34, 45]
v2 = [55, 25, 77]
v = list(map(lambda x: round(x[0]/x[1],3), zip(v1, v2)))
print("%s\n%s\n%s" %(v1, v2, v))
txt文件处理:
with open(txt_path) as f:
lines = f.readlines()
n = len(lines)
for i, line in enumerate(lines):
....
for line in lines:
line = line.strip().lower()
文件排序:
import re
def sort_by_file_name(dirnames):
dirs = dirnames
dirs = sorted(dirnames, key=lambda x: (int(re.sub('\D', '', x)), x))
return dirs
统计列表元素出现次数:
from collections import Counter
data = np.array([1.1,1.1,1.1,2,3,5,4,4,4,5])
# 方法一
print('Counter(data)\n',Counter(data)) # 调用Counter函数
# 方法二
print('np.unique(data)\n',np.unique(data)) # unique返回的是已排序数组
for i in np.unique(data):
print(np.sum(data==i)) # 对照unique数组,依次统计每个元素出现的次数
出现次数最多:
array = [1, 2, 3, 3, 2, 1, 0, 2]
print(max(array, key=array.count))
import numpy as np
from collections import Counter
data = np.array([1.1,2,3,4,4,5])
Counter(data) # {label:sum(label)}
#简单方法
sum(data==4)
产生一定范围内的随机数列表:
from random import randrange
[randrange(1, 10) for _ in range(5)]
图像转np array:
im = cv2.imread(r'G:/ai_data/new_seg/crop0610/test_dataset/f14800.jpg')
ar = np.array(im)
ar.shape
ar_flat = ar.flatten()
统计各像素值个数:
ar_flat.bincount(ttt)
y = ar_flat[ar_flat==0]
len(y)