classMyNumbers: def__iter__(self): self.a = 1 return self def__next__(self): self.a += 1 if self.a >= 10: raise StopIteration return self.a # usage 1 for x in myclass: # or for x in iter(myclass): print(x) if x > 5: break # usage 2 myiter = iter(myclass) next(myiter)
str
join split format ast.literal_eval
# a <class 'str'> or list(<class 'str'>) or tuple(<class 'str'>) a = 'gdfgdf' a = ['gdfgdf','hfgdhjfj'] ','.join(a) # 'g,d,f,g,d,f' # 'gdfgdf,hfgdhjfj'
# b <class 'str'> b = 'g,d,f,g,d,f' b = 'gdfgdf,hfgdhjfj' b.split(',') # ['g', 'd', 'f', 'g', 'd', 'f'] # ['gdfgdf', 'hfgdhjfj']
import numpy as np import matplotlib.pyplot as plt
x = np.arange(0, 5, 0.1) y = np.sin(x) plt.plot(x, y) # color https://blog.csdn.net/CD_Don/article/details/88070453
pause
import matplotlib.pyplot as plt import numpy as np
np.random.seed(19680801) data = np.random.random((50, 50, 50))
fig, ax = plt.subplots()
for i in range(len(data)): ax.cla() ax.imshow(data[i]) ax.set_title("frame {}".format(i)) plt.pause(0.1) # refer to: https://blog.csdn.net/mighty13/article/details/116671083
*trouble: why it becomes slower and slower when it handles many photos? The following pipeline has the same trouble (the two pipeline both use canvas):
# animation import matplotlib.pyplot as plt import numpy as np
x = np.linspace(0, 6*np.pi, 100) y = np.sin(x)
# You probably won't need this if you're embedding things in a tkinter plot... plt.ion()
fig = plt.figure() ax = fig.add_subplot(111) line1, = ax.plot(x, y, 'r-') # Returns a tuple of line objects, thus the comma
for phase in np.linspace(0, 10*np.pi, 500): line1.set_ydata(np.sin(x + phase)) fig.canvas.draw() fig.canvas.flush_events() # refer to: https://stackoverflow.com/questions/4098131/how-to-update-a-plot-in-matplotlib
sys
sys.path.append(path)
os
handle directory
import os filePath = 'C:\\myLearning\\pythonLearning201712\\carComments\\01\\' os.listdir(filePath)
# 查看当前工作目录 os.getcwd() # 修改当前工作目录 os.chdir( path ) # frequent use along os.mkdir(path)
# refer to https://blog.csdn.net/happyjacob/article/details/109279118 os.environ from environs import Env env = Env() SIM = env.str('SIM', 'fsdfds')
# walk import os path = r'./' ext = '.py' roots_dict = {} for root, dirs, files in os.walk(path): ''' root is a string, the path to the directory, consistent with 'path'. dirs is a list of the names of the subdirectories in root (excluding '.' and '..'). files is a list of the names of the non-directory files in root. Note that the names in the lists are just names, with no path components. To get a full path (which begins with top) to a file or directory in root, do os.path.join(root, name). ''' print('there are {} dir(s) and {} file(s) in the root of {}'.format( \ len(dirs), len(files), root)) roots_dict[root] = dirs + files
files_filter = [] if ext != None: for file in files: if os.path.splitext(file)[-1] in ext: files_filter.append(file) else: files_filter.extend(files) print('len(files_filter)', ': ', len(files_filter)) if len(files_filter) == 0: print() continue
# insert operation to process files_filter print() print(roots_dict)
from multiprocessing import Process, Manager, freeze_support, set_start_method
import time # optional
# create a new preocess using method 1: classMyNewProcess(Process): def__init__(self, mdic): self.mdic = mdic super().__init__() defrun(self): time_start = time.time() while (time.time() - time_start < 15): self.mdic["action"] += 2 print("subprocess1 action = ", self.mdic["action"]) time.sleep(1.6) # run 2/1=2 times per main while print("subprocess1 over!")
print("subprocess1 stop!")
# create a new preocess using method 2: defsubprocess2(mdic): time_start = time.time() while (time.time() - time_start < 11): mdic["action"] += 1 print("subprocess2 action = ", mdic["action"]) time.sleep(0.5) # run 2/0.5=4 times per main while print("subprocess2 over!")
print("subprocess2 stop!")
# main perocess where two precesses are created defmain(): # create global dict among processes manager = Manager() # must set after '__main__' mdic = manager.dict() mdic["action"] = 0
p = MyNewProcess(mdic, ) p.start() # to call p.run()