1

我想在 for 循环中设置键,并在另一个脚本中也使用循环将它们读回。为了测试 memcache 是否正常工作,我制作了这些简单的脚本:

一个.py

import pylibmc
mc = pylibmc.Client(["127.0.0.1"], binary=True,
        behaviors={"tcp_nodelay": True,
        "ketama": True})
mc["key_1"] = "Value 1"
mc["key_2"] = "Value 2"
mc["key_3"] = "Value 3"
mc["key_4"] = "Value 4"

b.py:

import pylibmc
mc = pylibmc.Client(["127.0.0.1"], binary=True,
        behaviors={"tcp_nodelay": True,
        "ketama": True})
print("%s" % (mc["key_1"]))
print("%s" % (mc["key_2"]))
print("%s" % (mc["key_3"]))
print("%s" % (mc["key_4"]))

这工作正常。但我不知道如何重写要在 for 循环中使用的 memcache 行。我尝试了几件事,但我尝试过的都没有奏效。我想要的是这样的:

for index in range (0,4):
   mc["key_(index)"] = "Value (index)"
4

1 回答 1

1

您可以使用 f 字符串:

for index in range (0,4):
    key = f"key_{index}"
    mc[key] = f"{mc[key]} {index}" # or "Value {index}"
于 2020-03-16T16:03:50.523 回答