赞
踩
str.find(str1)
a='dog'
>>> a.find('go') 不存在,局部也不行,返回-1
-1
>>> a.find('og') 存在,但不是从头开始一致,返回1
1
>>> a.find('do') 存在,包含和完全一致,返回0
0
直接对比 if a in b
str.isalnum() 所有字符都是数字或者字母
str.isalpha() 所有字符都是字母
str.isdigit() 所有字符都是数字
str.islower() 所有字符都是小写
str.isupper() 所有字符都是大写
str = "www.runoob.com"
print(str.upper()) # 把所有字符中的小写字母转换成大写字母
print(str.lower()) # 把所有字符中的大写字母转换成小写字母
print(str.capitalize()) # 把第一个字母转化为大写字母,其余小写
print(str.title()) # 把每个单词的第一个字母转化为大写,其余小写
WWW.RUNOOB.COM
www.runoob.com
Www.runoob.com
Www.Runoob.Com
split和strip的区别
split和strip的区别
查看字符编码ord(str)
ord('a')=97 查看字符编码id
小写字符ord编码 : 97-122
大写字符ord编码 : 65-90
if str in range(97,123) 判断单个字符是小写
字典形式
d = {key1 : value1, key2 : value2 }
创建字典 dic={}
赋值操作dic[key]=value
重复赋相同的值,只出现一次
查找操作 If key in dic
返回value, 查value是找不到的
按元素放入的先后顺序进行排序
import collections
dict = collections.OrderedDict()
from collections import defaultdict
d = defaultdict(list) # list只是属性声明,并不需要替换成真正定过后的list
d['a'].append(1)
d['a'].append(2)
d['b'].append(4)
多个值去重后再映射
d = defaultdict(set)
d['a'].add(1)
d['a'].add(2)
d['b'].add(4)
sorted_dict = dict(sorted(dur_dict.items(), key=lambda item: item[1]))
集合形式
basket = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana'}
a = set()
a.add('x')
如果已经有的是添加不上的a.remove('x')
list.append(x) 默认加在列表的最后一位
list.pop() 默认弹出的最后一位
list.remove(target) 移除特定的元素
list.reverse() 对列表进行翻转
list.index(obj) 找到对象obj的索引index
list.insert(index, obj) 在对应索引的位置插入对象
list.count(obj) 计算对象obj在index中出现的次数
list.extend(seq) 一次性在列表后添加多个数值, 也可以用 list1+list2 的形式
注意,弹出的时候要判断list是否为空,否则在严格的判断中是会报错的
a=list.pop() if list else '#'
list拼接a+b
列表和集合相互切换
mailto = ['cc', 'bbbb', 'afa', 'sss', 'bbbb', 'cc', 'shafa']
addr_to = list(set(mailto)) #列表去重
print(addr_to)
addr_to.sort(key=mailto.index) # 按照列表原顺序进行恢复
print(addr_to)
subtract_list = list(set(a).difference(set(b)))
tar_wav_list = list(filter(lambda x: x.startswith(start_str), wav_list)) ----将wav_list中元素1⃣️‘a'开头的挑选出来组成新的tar_wav_list
a=array([0,1,2]), a[::-1]------[2,1,0]
array([[1, 2, 4, 6], [1, 4, 5, 8]]) >>> a=np.array([[4,1,6,2],[5,1,4,8]]) >>> a array([[4, 1, 6, 2], [5, 1, 4, 8]]) >>> np.sort(a) array([[1, 2, 4, 6], [1, 4, 5, 8]]) # 直接展示数组从小到大排序后的结果,默认按行排序 >>> np.sort(a, axis=0) array([[4, 1, 4, 2], [5, 1, 6, 8]]) # 指定维度排序 >>> np.argsort(a) array([[1, 3, 0, 2], [1, 2, 0, 3]]) ## 将数组a按照从小到大的结果展示index,然后可以选择最大的几维
>>> int(1.799999)
1
>>> round(1.799999)
2
condition = data_array>1
f0_array = np.extract(condition, data_array) --------将数组中数值大于1的挑选出来,组成新的f0_array
np.load(input_file, mmap_mode = 'r')
#输入
2
1 5
10 20
输出
6
30
import sys
lines = list(sys.stdin)
#对第一行单独处理
t = int(lines[0].strip())
for n in lines[1:]:
n = list(n.split(' '))
print(int(n[0])+int(n[1]))
或者
#第一行单独处理
t = int(input())
while True:
try:
line = list(map(int, input().strip().split()))
print(line[0]+line[1])
except:
break
输入包括两个正整数a,b(1 <= a, b <= 10^9),输入数据有多组, 如果输入为0 0则结束输入
输入
1 5
10 20
0 0
输出
6
30
while True:
try:
line = list(map(int, input().strip().split()))
# line每次读到的是一行
if line[0]==0 & line[1]==0:
break
else:
print(line[0]+line[1])
except:
break
attention
a.split(‘_ ‘) 和a.split()效果一样,a.split(’’)报错
>>> a='a mk ll'
>>> a.split()
['a', 'mk', 'll']
>>> a.split('')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: empty separator
>>> a.split(' ')
['a', 'mk', 'll']
输入
5
c d a bb e
输出
a bb c d e
n = int(input())
while True:
try:
line = list(input().split())
line.sort()
print(' '.join(line))
except:
break
attention
想要的输出是序列而不是列表
a=['a', 'b', 'c']
>>> print(a)
['a', 'b', 'c']
>>> print(' '.join(a))
a b c
>>> print(''.join(a))
abc
输入
a,c,bb
f,dddd
nowcoder
输出
a,bb,c
dddd,f
nowcoder
while True:
try:
line = list(input().split(','))
line.sort()
print(','.join(line))
except:
break
参考:OJ在线编程常见输入输出练习场 https://ac.nowcoder.com/acm/contest/320#question
import multiprocessing as mp
def copy_file(name): # 处理单个文件的函数
xxxx
pool = mp.Pool(mp.cpu_count()) # 也可以指定线程个数
# pool.map(function, list)
pool.map(copy_file, subtract_list)
pool = multiprocessing.Pool(processes=4) # Example: using 4 processes
# Apply the process_func to each item in datalists using the pool
results = []
for result in tqdm(pool.imap_unordered(extract_vq_feature, datalists), total=len(datalists)):
results.append(result)
# Close the pool
pool.close()
pool.join()
子进程和主进程结束时间冲突会报错daemonic processes are not allowed to have children
参考多种方法实现python线程池(threadpool模块\multiprocessing.dummy模块\concurrent.futures模块)
from concurrent.futures import ThreadPoolExecutor,ProcessPoolExecutor import os,time def task(n): print('%s is runing进程号' %os.getpid()) time.sleep(2) return n**2 def main(): start_time = time.time() with ThreadPoolExecutor(max_workers=3) as executor: futures = executor.map(task, [i for i in range(10)]) print('*'*20) for future in futures: print(future) print('用时共: %s second' % (time.time() - start_time)) if __name__ == '__main__': main()
import threading, time def doWaiting(): print('start waiting1: ' + time.strftime('%H:%M:%S') + "\n") time.sleep(3) print('stop waiting1: ' + time.strftime('%H:%M:%S') + "\n") def doWaiting1(): print('start waiting2: ' + time.strftime('%H:%M:%S') + "\n") time.sleep(8) print('stop waiting2: ', time.strftime('%H:%M:%S') + "\n") thread1 = threading.Thread(target = doWaiting) thread1.start() thread2 = threading.Thread(target = doWaiting1) thread2.start() thread1.join() ## 阻塞,所有的进程执行完再推出 thread2.join()
输出的结果:
start waiting1: 14:14:08
start waiting2: 14:14:08
stop waiting1: 14:14:11
stop waiting2: 14:14:16
thread1 = threading.Thread(target = doWaiting)
thread1.start()
thread1.join()
t1 = doWaiting() ####主进程
thread2 = threading.Thread(target = doWaiting)
thread2.start()
thread2.join()
执行结果:前一个进程启动join阻塞,下一个进程还没有start,就会等待这个进程结束再开始下一个进程,但是不会阻塞主进程
start waiting1: 14:18:45 //进程1
start waiting1: 14:18:45 //主进程
stop waiting1: 14:18:48
stop waiting1: 14:18:48
start waiting2: 14:18:48 //进程2
stop waiting2: 14:18:56
from threading import Thread # _sum = 0 def cal_sum(begin, end): # global _sum _sum = 0 for i in range(begin, end + 1): _sum += i return _sum """重新定义带返回值的线程类""" class MyThread(Thread): def __init__(self, func, args): super(MyThread, self).__init__() self.func = func self.args = args def run(self): self.result = self.func(*self.args) def get_result(self): try: return self.result except Exception: return None if __name__ == '__main__': t1 = MyThread(cal_sum, args=(1, 5)) t2 = MyThread(cal_sum, args=(6, 10)) t1.start() t2.start() t1.join() t2.join() res1 = t1.get_result() res2 = t2.get_result() print(res1 + res2)
输出55
import json
data=[{"startTime":"0.00","endTime":"5.67","content":"来关注境外疫情,澳大利亚维多利亚州州长丹尼尔·安德鲁斯七月六号宣布。 ", "userExtraContent":"女","correct":"正确"},{"startTime":"5 .69","endTime":"11.21","content":"从七号起无限期关闭与新南威尔士州的边界,以防止新冠病毒蔓延。","userExtraContent":"女 ","correct":"正确"},{"startTime":"11.24","endTime":"15.70","content":"维多利亚州近期再次暴发令人担忧的疫情,据路透社报道。","userExtraContent":"女","correct":"正确"}]
读入json格式json.loads(data)
,然后安装列表,读到字典,再根据key读到字典value
在读出或写入的时候,加入encoding= 'utf-8'
的注释,中间的dict/set/list都可以正常调用
字典写出和读入
dict={'李明':1, '张三':2}
f = open('test01.txt', 'w', encoding= 'utf-8')
f.write(str(dict))
f.close()
f = open('test01.txt', 'r', encoding= 'utf-8')
a = f.read()
dict = eval(a)
print(dict['李明'])
str(dict)
eval(str)
“ ".join(list)
import datetime
starttime = datetime.datetime.now()
#long running
#do something other
endtime = datetime.datetime.now()
print (endtime - starttime).seconds
>>> from pathlib import Path >>> a='experiments-train/WaveRNN/mel_wavernn' >>> a=Path(a) >>> a PosixPath('experiments-train/WaveRNN/mel_wavernn') >>> a.parent----相当于os.path.dirname PosixPath('experiments-train/WaveRNN') >>> a.parent/'mel' ----------相当于os.path.join() PosixPath('experiments-train/WaveRNN/mel') >>> a=Path('experiments-train/WaveRNN/mel_wavernn/01.txt') >>> a.name------------相当于os.path.basename '01.txt' filename = Path("source_data/text_files/raw_data.txt") print(filename.name) # prints "raw_data.txt" print(filename.suffix) -------------文件后缀 # prints "txt" print(filename.stem) ------------文件裸名字 # prints "raw_data" if not filename.exists(): print("Oops, file doesn't exist!") else:
plt.bar(range(len(num_list)), num_list)
time = np.arange(len(src_f0_data))
fig = plt.figure()
plt.plot(time, src_f0_data,'r--',label='src_f0')
plt.plot(time, pred_f0_data,'g--',label='pred_f0')
plt.xlabel('time')
plt.ylabel('logf0')
plt.legend()
fig.set_size_inches(15, 5) ----在此基础上小幅度调整,更大的速度&加载都会很慢
plt.savefig(fig_path, format='png')
def plot_pitch_phn(pitch_path, phn_path, save_dir): pitch = np.load(pitch_path) pitch = pitch.reshape(-1) phn = open(phn_path, encoding='utf-8-sig').readlines() phn = [i.strip() for i in phn] #print(phn) phn = process_phn_acc_PitchLength(phn) #print('phn:', len(phn), 'pitch', pitch.shape) print(phn) assert len(phn)==len(pitch) fig_name = os.path.basename(pitch_path).split('.')[0] print(fig_name) fig_path = os.path.join(save_dir, '%s.png'%fig_name) x = range(len(pitch)) plt.figure(figsize=(20,3)) #放在前边 plt.plot(x, pitch, label=fig_name) plt.xticks(x, phn) #plt.rcParams['figure.figsize'] = (5, 1) plt.legend() plt.savefig(fig_path)
cmd = 'xxxx' #shell
result = subprocess.getstatusoutput(cmd)
print(result)
python -W ignore xx.py
raise ValueError(error information)
try:
条件1
except Exception: -----except 异常类型(比如 IOError, Exception--常规错误基类)
条件2 --------条件1异常则执行条件2
举个栗子
a=1
try:
if a>2:
a += 2
else: #### 单独的if 条件false并不会进入Exception。要在条件判断中调起;或者直接一个执行条件不合适会启动Exception
raise Exception
except Exception:
print('error: a is ',a)
print失效
为了判断是否进入某一小段命令,有时会使用print debug,但是因为程序执行过程中错误类型不同,可能print的结果并么有打印出来,这时候可以添加 print(error information, flush=True)
,会避免print中的内容被冲掉没有输出;
flush
清空缓冲区内容
args
print('--------args----------')
for k in list(vars(args).keys()):
print('%s: %s' % (k, vars(args)[k]))
print('--------args----------\n')
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。