python redis list操作_python操作redis list

上一篇文章写了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 没在这里实现,详细可查看上篇文章(上面超链接)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值