Redis:如何解析列表结果 [英] Redis: How to parse a list result
问题描述
我正在像这样在 Redis 中存储一个列表:
I am storing a list in Redis like this:
redis.lpush('foo', [1,2,3,4,5,6,7,8,9])
然后我会像这样返回列表:
And then I get the list back like this:
redis.lrange('foo', 0, -1)
我得到了这样的东西:
[b'[1, 2, 3, 4, 5, 6, 7, 8, 9]']
如何将其转换为实际的 Python 列表?
How can I convert this to actual Python list?
此外,我在 RESPONSE_CALLBACKS
中没有看到任何可以提供帮助的定义?我错过了什么吗?
Also, I don't see anything defined in RESPONSE_CALLBACKS
that can help? Am I missing something?
一个可能的解决方案(在我看来很糟糕)可以是:
A possible solution (which in my opinion sucks) can be:
result = redis.lrange('foo',0, -1)[0].decode()
result = result.strip('[]')
result = result.split(', ')
# lastly, if you know all your items in the list are integers
result = [int(x) for x in result]
更新
好的,我找到了解决方案.
Ok, so I got the solution.
实际上,lpush
函数期望将所有列表项作为参数传递,而不是作为单个列表传递.redis-py 源码中的函数签名说的很清楚...
Actually, the lpush
function expects all the list items be passed as arguments and NOT as a single list. The function signature from redis-py source makes it clear...
def lpush(self, name, *values):
"Push ``values`` onto the head of the list ``name``"
return self.execute_command('LPUSH', name, *values)
我在上面所做的是发送一个列表作为参数,然后将其作为单个项目发送到 redis.
What I am doing above is send a single list as an argument, which is then sent to redis as a SINGLE item.
我应该按照答案中的建议打开列表:
I should be unpacking the list instead as suggested in the answer:
redis.lpush('foo', *[1,2,3,4,5,6,7,8,9])
返回我期望的结果...
which returns the result I expect...
redis.lrange('foo', 0, -1)
[b'9', b'8', b'7', b'6', b'5', b'4', b'3', b'2', b'1']
推荐答案
我认为您遇到的语义类似于 list.append() 和 list 之间的区别.扩展().我知道这对我有用:
I think you're bumping into semantics which are similar to the distinction between list.append() and list.extend(). I know that this works for me:
myredis.lpush('foo', *[1,2,3,4])
... 注意列表前面的 *(map-over)运算符!
... note the * (map-over) operator prefixing the list!
这篇关于Redis:如何解析列表结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!