看崔大佬的书,它连接redis使用的是StrictRedis,但是有序集合的操作zadd(name,*args,**kwargs)会报错,查看资料发现应该是zadd(name,iteritems)。
redis数据库中有序集合的操作
1,添加
from redis import StrictRedis redis = StrictRedis(host='localhost',port=6379,db=0,password='foobared')
#向键grade的添加元素Bob分数为98 redis.zadd('grade',{'Bob':98,'Mike':80})
2,删除
redis = StrictRedis(host='localhost',port=6379,db=0,password='foobared')
#删键grade的元素Mike redis.zrem('grade','Mike')
3,存在执行,不存在添加
redis = StrictRedis(host='localhost',port=6379,db=0,password='foobared') #如果grade中存在Bob的元素则分数进行-2操作,否则添加 redis.zincrby('grade',-2,'Bob')
4,获取元素的排名
redis = StrictRedis(host='localhost',port=6379,db=0,password='foobared') #获取grade中元素的排名 amy = redis.zrank('grade','吴志斌') print(amy)
5,获取倒序
from redis import StrictRedis redis = StrictRedis(host='localhost',port=6379,db=0,password='foobared') #获取grade中元素的倒序排名 amy = redis.zrevrank('grade','吴志斌') print(amy)
6,获取范围的元素
from redis import StrictRedis redis = StrictRedis(host='localhost',port=6379,db=0,password='foobared') #获取grade中排名列表 amy = redis.zrevrange('grade',0,3) print(amy)
7,获取分数范围内的元素
from redis import StrictRedis redis = StrictRedis(host='localhost',port=6379,db=0,password='foobared') #获取80-100分数范围的元素 grade = redis.zrangebyscore('grade',80,100) print(grade)
8,返回分数范围的元素个数
from redis import StrictRedis redis = StrictRedis(host='localhost',port=6379,db=0,password='foobared') #返回80-100分数范围的元素个数 grade = redis.zcount('grade',80,100) print(grade)
9,获取键中元素的个数
from redis import StrictRedis redis = StrictRedis(host='localhost',port=6379,db=0,password='foobared') #获取键grade表中的元素个数 grade = redis.zcard('grade') print(grade)
10,按排名删除元素
from redis import StrictRedis redis = StrictRedis(host='localhost',port=6379,db=0,password='foobared') #获取键grade表中排名1-3的元素 grade = redis.zremrangebyrank('grade',0,2) print(grade)
返回删除元素的个数
11,删除分数范围的元素
from redis import StrictRedis redis = StrictRedis(host='localhost',port=6379,db=0,password='foobared') # 删除键grade中分数范围100-140的元素 redis.zremrangebyscore('grade',100,140)
返回的是删除元素的个数
12,