random模块的使用demo
import random # 调用random模块
a = random.random() # 随机从0-1之间(包括0不包括1)抽取一个小数
print(a)
a = random.randint(0,100) # 随机从0-100(包括0和100)之间抽取一个数字
print(a)
a = random.choice('abcdefg') # 随机从字符串,列表等对象中抽取一个元素(可能会重复)
print(a)
a = random.sample('abcdefg', 3) # 随机从字符串,列表等对象中抽取多个不重复的元素
print(a)
items = [1, 2, 3, 4, 5, 6] # “随机洗牌”,比如打乱列表
random.shuffle(items)
print(items)
查看某个模块的的函数(函数和类方法)
import random # 调用random模块
print(dir(random))
执行结果
bash:31b204c1-12a4-7051-6aad-1b6c696f3b1c$ python /classroom/apps-1-id-5cd9766619bbcf00015547c7/31b24c1-12a4-7051-6aad-1b6c696f3b1c/main.py
['BPF', 'LOG4', 'NV_MAGICCONST', 'RECIP_BPF', 'Random', 'SG_MAGICCONST', 'SystemRandom', 'TWOPI', '_Sequence', '_Set', '__all__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', '_accumulate', '_acos', '_bisect', '_ceil', '_cos', '_e', '_exp', '_inst', '_log', '_os', '_pi', '_random', '_repeat', '_sha512', '_sin', '_sqrt', '_test', '_test_generator', '_urandom', '_warn', 'betavariate', 'choice', 'choices', 'expovariate', 'gammavariate', 'gauss', 'getrandbits', 'getstate', 'lognormvariate', 'normalvariate', 'paretovariate', 'randint', 'random', 'randrange', 'sample', 'seed', 'setstate', 'shuffle', 'triangular', 'uniform', 'vonmisesvariate', 'weibullvariate']
对于查到的结果"__xx__"
结构的(如__doc__
),它们是系统相关的函数,我们不用理会,直接看全英文的函数名即可。
csv的使用
import csv
with open("test.csv",newline = '') as f:
reader = csv.reader(f)
#使用csv的reader()方法,创建一个reader对象
for row in reader:
#遍历reader对象的每一行
print(row)
print("读取完毕!")
执行结果
['6', '7', '8', '9', '10']
['11', '12', '13', '14', '15']
['16', '17', '18', '19', '20']
['21', '22', '23', '24', '25']
['26', '27', '28', '29', '30']
['31', '32', '33', '34', '35']
['36', '37', '38', '39', '40']
读取完毕!
已经读取出来了,那么我们如何写入呢?这样就可以看如下图了
peace!
今天的分享到此结束。