copy模块
可以用来复制对象、列表
copy只是浅拷贝,对原对象的更改也会造成拷贝对象的改变,但是在原列表中添加,不会出现在拷贝后的列表中。
要想拷贝出一个完全不同的东西,要用深拷贝deepcopy,即拷贝过后,对原对象的任何操作,都不会影响拷贝出来的那个。
import copy
ans=copy.copy(animal)
ans=copy.deepcopy(animal)
import copy
>>> class car:
pass
>>> car1=car()
>>> car1.wheels=44
>>> car2=car1
>>> car2.wheels=33
>>> car1.wheels
33
>>> car3=copy.copy(car1)
>>> car3.wheels =66
>>> car1.wheels
33
keyword模块
记录所有的Python关键字。
iskeyword来判断是关键字则返回True,反之为False;kwlist打印出所有的关键字,会随着Python版本而有所不同。
>>> keyword.iskeyword ('if')
True
>>> keyword.iskeyword ('hah')
False
>>> keyword.kwlist
['False', 'None', 'True', 'and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']
random模块
randint(left,right)用来生成随机数,闭区间
import random
>>> ans=random.randint(1,100)
>>> while(True):
print('guess a number')
x=int(input())
if(x==ans):
print('you are right')
break
elif (x<ans):
print('try bigger')
else:
print('try smaller')
choice()在列表中随机选择一个元素,shuffle()相当于洗牌,把列表元素重新随机排列(打乱)
ans=['a','b','c','dd','fdf','ad']
>>> ans
['a', 'b', 'c', 'dd', 'fdf', 'ad']
>>> random.choice(ans)
'a'
>>> random.choice(ans)
'ad'
>>> random.choice(ans)
'fdf'
>>> random.shuffle (ans)
>>> ans
['b', 'c', 'ad', 'fdf', 'dd', 'a']
>>>
sys模块
有一些系统函数,用来控制shell程序自身
exit()推出程序
stdin中的,readline(n),可以指定接收输入数据的个数,(可以参略)包括空格,以换行符结尾。此区别于input()
stdout中的write(),向控制台输出信息,并能返回输出字符的个数
import sys
sys.exit()
v=sys.stdin.readline(25)
chenyu tin hahah asda1231 24 324 2
v
>>> 'chenyu tin hahah asda123'
ans=input('please')
please4657676hahahhajspaojs japdspo a
ans
>>> '4657676hahahhajspaojs japdspo a'
ans=sys.stdout.write('chhahach aad123 ')
>>> chhahach aad123
time模块
time得出的时间是从1970.1.1以来的秒数,可以用两个时间的差值来计算某个函数的执行时间。
time.time()
1521982531.0341218
def cnt(max):
t1=time.time()
for x in range(0,max):
print(x)
t2=time.time()
print('%s '%(t2-t1))
cnt(100)
asctime()或者没有、或者以元组为参数(即内容无法修改的形似列表的东西),把按照指定形式写好的元组转换称asctime指定的格式输出。
localtime()返回当前时间,也可以用索引的方式访问。
import time
>>> time.asctime()
'Sun Mar 25 21:12:35 2018'
>>> time.localtime()
time.struct_time(tm_year=2018, tm_mon=3, tm_mday=25, tm_hour=21, tm_min=13, tm_sec=40, tm_wday=6, tm_yday=84, tm_isdst=0)
>>> t=time.localtime ()
>>> t[0]
2018
>>> t[1]
3
>>> t[2]
25
>>> t[3]
21
>>>
sleep(s)
让程序执行到此处时暂停s秒
for x in range(1,15):
time.sleep(1)
print(x)
两种引入模块的方式比较
import 模块名
import turtle
t=turtle.Pen()
from 模块名 import *
from turtlr import *
t=Pen()
使用后面一种方法,可以在使用模块中的函数时,不再加上模块名,少敲代码。