1.random
import random
1.1 randint
help(random.randint)
Help on method randint in module random:
randint(a, b) method of random.Random instance
Return random integer in range [a, b], including both end points.
random.randint参考帮助文档,返回值是闭区间[a, b]
for i in range(10):
print(random.randint(0, 1), end='')
0000101110
1.2 choice
随机选取一个元素
l = [random.randint(1,100) for i in range(10)]
print(l)
[86, 68, 74, 13, 9, 24, 23, 65, 99, 7]
print(random.choice(l))
13
books = ['C++ Primer', 'Python Cookbook', 'Thinking in JAVA', 'Learning Python']
print(random.choice(books))
C++ Primer
1.3 shuffle
print(books)
['C++ Primer', 'Python Cookbook', 'Thinking in JAVA', 'Learning Python']
random.shuffle(books)
print(books)
['Learning Python', 'Thinking in JAVA', 'Python Cookbook', 'C++ Primer']
2. pickle
class Dog():
def __init__(self, name, weight, color):
self.name = name
self.weight = weight
self.color = color
def sayHello(self):
print("{} weights {} with {}, says hello to everyone".format(self.name,self.weight,self.color))
QQ = Dog('QiuQiu', weight=3.5, color='dark brown')
QQ.sayHello()
QiuQiu weights 3.5 with dark brown, says hello to everyone
GG = Dog('GuoGuo', 2.5, 'light brown')
GG.sayHello()
GuoGuo weights 2.5 with light brown, says hello to everyone
写入文件
import pickle
MyDogs = {dog.name:dog for dog in [QQ, GG]}
print(MyDogs)
save_file = open('My Dogs.data', 'wb')
pickle.dump(MyDogs, save_file)
save_file.close()
{'QiuQiu': <__main__.Dog object at 0x108167a90>, 'GuoGuo': <__main__.Dog object at 0x1081767f0>}
读取
load_file = open('My Dogs.data', 'rb')
HerDogs = pickle.load(load_file)
print(HerDogs)
{'QiuQiu': <__main__.Dog object at 0x107f8ef28>, 'GuoGuo': <__main__.Dog object at 0x108220b38>}
HerDogs['QiuQiu'].weight = 4.0
MyDogs['QiuQiu'].sayHello()
QiuQiu weights 3.5 with dark brown, says hello to everyone
HerDogs['QiuQiu'].sayHello()
QiuQiu weights 4.0 with dark brown, says hello to everyone
另一个例子
play_data = {
'name': 'QQ',
'money': 10000,
'owner': ['BB', 'MM']
}
save_file = open('save.data','wb')
pickle.dump(play_data, save_file)
save_file.close()
load_file = open('save.data','rb')
data = pickle.load(load_file)
print(data)
{'name': 'QQ', 'money': 10000, 'owner': ['BB', 'MM']}