格式化随机模块函数的输出



我正在为自己编写一个程序,为我玩的这个游戏生成一个装备。我快完成了,我从使用 random.choice 切换到 random.sample,以避免结果重复但讨厌格式。

print("He has", random.choice(kills) + ',', random.choice(kills) + ',', random.choice(kills) + ', and', random.choice(kills))

输出:

他有双手扼流圈、串、串和干草叉刺

而:

print("He has", random.sample(kills, 4))

输出:

他有["膝盖折断","下巴撕裂","身体猛击","窒息"]

如何获得输出类似 random.choice(( 代码的示例?谢谢!

random = random.sample(kills, 4)
str_random = ", ".join(str(x) for x in random[:-1])
print("He has", str_random, "and", random[-1])

执行此操作的一种方法是遍历对象,将其添加到字符串中。请尝试以下操作:

choices = random.sample(kills,4) #put choices in variable
s = "He has " #begin output String
for(c in choices):
    s = s + c + "," #add choices to output string
s = s[:-1] #remove final comma
print(s) #print string

最新更新