上一篇文章写了redis客户端的各种list操作,这篇文章用python客户端来复现一下。(建议结合上篇文章看,效果更佳)
from redis import Redis
if __name__ == '__main__':
client = Redis(host='192.168.174.129', port=6666, decode_responses=True)
try:
# 左右插入
print(client.rpush('list1', 1, 'a', 2)) # 3
print(client.lpush('list1', 0, -1))# 5
# 还有 rpushx/lpushx 存在才push
print(client.lrange('list1', 0, -1))# ['-1', '0', '1', 'a', '2']
# before/after 插入
print(client.linsert('list1', 'before', 'a', 1.5)) # 6
print(client.lrange('list1', 0, -1)) # ['-1', '0', '1', '1.5', 'a', '2']
print(client.linsert('list1', 'after', 'a', 'b')) # 7
print(client.lrange('list1', 0, -1)) # ['-1', '0', '1', '1.5', 'a', 'b', '2']
# 测试列表里面有2个相同的value,在insert的时候,如何插入
print(client.rpush('list2', 1, 'a', 2, 'a', '3')) # 5
print(client.linsert('list2', 'before', 'a', 1.5)) # 6
print(client.lrange('list2', 0, -1)) # ['1', '1.5', 'a', '2', 'a', '3']
# lpop/rpop
print(client.lpop('list2')) # 1
print(client.rpop('list2')) # 3
client.rpush('list3', 1, 'a', 2, 'a', '3', 'a', 4, 'a', 5, 'a')
client.rpush('list4', 1, 'a', 2, 'a', '3', 'a', 4, 'a', 5, 'a')
client.rpush('list5', 1, 'a', 2, 'a', '3', 'a', 4, 'a', 5, 'a')
# lrem
print(client.lrem('list3', 2, 'a')) # 2
print(client.lrange('list3', 0, -1)) # ['1', '2', '3', 'a', '4', 'a', '5', 'a']
print(client.lrem('list4', -2, 'a')) # 2
print(client.lrange('list4', 0, -1)) # ['1', 'a', '2', 'a', '3', 'a', '4', '5']
print(client.lrem('list5', 0, 'a')) # 5
print(client.lrange('list5', 0, -1)) # ['1', '2', '3', '4', '5']
# ltrim
print(client.ltrim('list5', 2, 4)) # True
print(client.lrange('list5', 0, -1)) # ['3', '4', '5']
# lindex
print(client.lindex('list5', -1)) # 5
print(client.lindex('list5', -3)) # 3
print(client.lindex('list5', -0)) # 3
# llen
print(client.llen('list5')) # 3
# lset
print(client.lset('list5', 2, 33)) # True
print(client.lrange('list5', 0, -1)) # ['3', '4', '33']
# rpoplpush
print(client.lrange('list4', 0, -1)) # ['1', 'a', '2', 'a', '3', 'a', '4', '5']
print(client.rpoplpush('list4', 'list5')) # 5
print(client.lrange('list4', 0, -1)) # ['1', 'a', '2', 'a', '3', 'a', '4']
print(client.lrange('list5', 0, -1)) # ['5', '3', '4', '33']
print(client.rpoplpush('list5', 'list5')) # 33
print(client.lrange('list5', 0, -1)) # ['33', '5', '3', '4']
print(client.rpoplpush('notExist', 'list5')) # None
print(client.lrange('list5', 0, -1)) # ['33', '5', '3', '4']
except Exception as e:
print(e)
finally:
client.close()
brpop / blpop / brpoplpush 没在这里实现,详细可查看上篇文章(上面超链接)