Python random, pickle

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']}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值