Python,redis:如何一次设置多个键值对

时间:2017-02-16 15:42:08

标签: python redis set pipeline

我有两个清单 keys = [k0,k1,.... kn] vals = [v0,v1,...... vn]

我可以通过多个步骤在redis上设置这些键值,执行以下操作: for i in range(0,len(keys)): redis_con.set(keys[i], vals[i]) 但这是多组操作。 如何在一个异步步骤中执行此操作?

3 个答案:

答案 0 :(得分:1)

keys= ["k0","k1"] 
vals= ["v0","v1"]
# use zip or izip based on py 
res = set(zip(keys, vals))
print res
>>> set([('k0', 'v0'), ('k1', 'v1')])

答案 1 :(得分:1)

您也可以使用这种方式使用自定义方法:

a = [["b", "k", "a"], ["c", "m", "a"], ["a", "j","c"]]
b = [["k","a", "l"], ["l", "f", "c"], ["c", "d", "b"]]

def get_sets(*args):
    final = []
    for v in args:
        for j in v:
            final.append(set(j))
        yield final
        final = []

print(list(get_sets(a,b))) 

输出:

[
  [
   {'b', 'k', 'a'}, {'c', 'a', 'm'}, {'c', 'j', 'a'}
  ],
  [
   {'l', 'k', 'a'}, {'c', 'f', 'l'}, {'c', 'd', 'b'}
  ]
]

答案 2 :(得分:1)

假设你想要一个redis调用set ops:

pipe = redis_con.pipeline()
for i in range(0,len(keys)):
  pipe.set(keys[i], vals[i])
pipe.execute()