如何在变量名称中使用.format(或其他格式)?

时间:2019-09-16 13:46:19

标签: python-3.x variables formatting

我有一些代码,其中包含6个列表(Group1,Group2,Group3等)。

我想使用样本函数从列表之一中抽取4个随机项。我希望样本看起来像这样:sample(Group{0}.format(randrange(6), 4)

但是该功能不起作用。是否有类似这种情况的东西。

我已经尝试过.format的方法,但是这种方法不起作用。 我已经在互联网上搜索了答案,但是找不到答案。

是否存在类似的解决方案?

Possible_Signs0 = ["O", "AT", "Golf", "Hartbeat", "Octopus", "JL", "ReverseC."]
Possible_Signs1 = ["ReverseE..", "O", "ReverseC.", "Oink", "WhiteStar", "JL", "Reverse?"]
Possible_Signs2 = ["Copyright", "WwithEye", "Oink", "b2bK", "RRR", "Golf", "WhiteStar"]
Possible_Signs3 = ["6", "Music", "BwithWings", "Octopus", "b2bK", "Reverse?", "Smiley"]
Possible_Signs4 = ["3tooth", "Smiley", "BwithWings", "C.", "Music", "Shrek3", "BlackStar"]
Possible_Signs5 = ["6", "ReverseE..", "Stitch", "ae", "3Tooth", "H", "Omega"]

Used_signs = sample(Possible_Signs + randrange(6), 4)
print(Used_signs)

它应该从一个随机的Possible_signsN组中打印一个样本。

1 个答案:

答案 0 :(得分:0)

您无法真正做到准确您想要的内容-有关原因的更多详细信息,请参见this answer

但是如果您稍微更改代码,则可以执行类似的操作:

signs_dict = {
    "Possible_Signs1": ["ReverseE..", "O", "ReverseC.", "Oink", "WhiteStar", "JL", "Reverse?"],
    "Possible_Signs2": ["Copyright", "WwithEye", "Oink", "b2bK", "RRR", "Golf", "WhiteStar"],
    "Possible_Signs3": ["6", "Music", "BwithWings", "Octopus", "b2bK", "Reverse?", "Smiley"],
    "Possible_Signs4": ["3tooth", "Smiley", "BwithWings", "C.", "Music", "Shrek3", "BlackStar"],
    "Possible_Signs5": ["6", "ReverseE..", "Stitch", "ae", "3Tooth", "H", "Omega"],
}

mykey = 'Possible_Signs{}'.format(randrange(6))
used_signs = sample(signs_dict[mykey], 4)

print(used_signs)