我有一个 csv 文件,其中每一行都包含一个人的 ID #,然后是一堆属性。我希望能够为每个人创建一个包含他们所有属性的元组,然后将元组命名为他们 ID # 的一些变体。
然后所有这些元组将被添加到 redis 中的一个集合中进行存储。
我似乎无法弄清楚如何创建一个以人员 ID# 命名的元组。
我知道动态命名变量不是最佳实践,但我宁愿不将所有元组放在列表中或设置为然后放入 redis 集(这是必须的);它看起来效率低下且麻烦。
这是我现在的代码:
with open('personlist.csv','rb') as f:
for line in f:
row = line.split(',')
personID = row[0]
attrb1 = row[1]
attrb2 = row[2]
attrb3 = row[3]
# Need to name tuple here and define as (attrb1, attrb2, attrb3)
r.lpush('allpersonslist',tuple)
最佳答案
此示例需要额外的代码才能运行。我假设您使用的是 redis API,例如 redis-py。变量 r
是一个打开的 redis 连接。
import pickle
with open('personlist.csv', 'rb') as f:
for line in f:
row = line.split(',')
personID = row[0]
attrb1 = row[1]
attrb2 = row[2]
attrb3 = row[3]
#put the attributes in a tuple
tuple = (attrb1, attrb2, attrb3)
#serialize the tuple before adding it to the set
r.set("person/%d" %personID,pickle.dumps(tuple,-1))
def getPerson(Id):
return pickle.loads(r.get("person/%d" %Id))
您可以调用 getPerson(5)
返回与 ID 为 5 的人关联的元组。
关于python - 为redis动态命名元组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22029711/