You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何去除Python派对游戏代码输出中的括号、圆括号与逗号,生成整洁语句

如何去除Python派对游戏代码输出中的括号、圆括号与逗号,生成整洁语句

嘿,我懂你遇到的这个小麻烦——那些输出里的('Gerald',)格式完全破坏了派对游戏的沉浸感对吧?问题根源其实很简单,咱们来一步步搞定它:

问题出在哪?

你现在用的是这种写法来选随机人物:

person = (*random.sample(people, k=1),)

random.sample(people, k=1)本身返回的是一个只包含一个元素的列表(比如["Gerald"]),而你用(*...,)的语法把这个列表拆包成了一个元组(结果就是('Gerald',))。当你把这个元组转成字符串打印时,自然就会带上括号和逗号了。

最简单的解决方案

我们不需要把结果转成元组,直接拿到单个字符串就好,有两种轻松的方式:

方式1:直接取列表的第一个元素

如果坚持用random.sample,只需要在结果后面加[0]来取出唯一的元素:

person = random.sample(people, k=1)[0]
person1 = random.sample(people, k=1)[0]
person2 = random.sample(people, k=1)[0]
person3 = random.sample(people, k=1)[0]

方式2:用random.choice()更省心

既然你每次只需要选一个随机元素,random.choice()是专门干这个的——它直接返回单个元素,不用处理列表,写法更简洁:

person = random.choice(people)
person1 = random.choice(people)
person2 = random.choice(people)
person3 = random.choice(people)

额外的小优化

你的代码里,当权重都是1的时候,random.choices(Locations, weights=weights, k=1)[0]完全可以换成random.choice(Locations),效果一样但代码更清爽。比如:

location = random.choice(Locations)
weapon = random.choice(Weapons)
causeofdeath = random.choice(cod)
message = random.choice(messages)

修改后的完整代码

这里是调整好的完整代码,打印出来的语句就会是你想要的整洁格式啦:

people = ["the boogie man"]
while True:
    item = input("Enter a person (or 'q' to quit): ")
    if item.lower() == 'q':
        break
    people.append(item)
print(people)

import random
# 用random.choice直接获取单个人名字符串
person = random.choice(people)
person1 = random.choice(people)
person2 = random.choice(people)
person3 = random.choice(people)

Locations = ["the lagoon", "the basement", "the dark forest", "the kitchen", "the backyard", "the batcave"]
location = random.choice(Locations)

Weapons = ["flintlock pistol", "shotgun", "AK-47", "steak knife", "butter knife", "fork", "infant child", "batman"]
weapon = random.choice(Weapons)

cod = ["poisioned bagels", "a seigure", "a todler with a plastic spoon", "slippery floor sign not being on the slippery floor"]
causeofdeath = random.choice(cod)

messages = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13"]
message = random.choice(messages)

if message == "1":
    print(f"{person} killed {person1} with a {weapon} and hid the body in {location}")
if message == "2":
    print(f"{person} saved {person1} from {person2} who was trying to kill them using a {weapon}")
if message == "3":
    print(f"{person} swears they are innocent")
if message == "4":
    print(f"{person} paid {person1} to kill {person2} with a {weapon}")
if message == "5":
    print(f"{person} framed {person1} for {person2}'s murder")

(另外我还把字符串拼接改成了f-string,这样写法更直观,也不容易出错~)

现在运行代码,你就能得到像Gerald was killed with a frying pan这样干净的语句了,完美适配你的派对游戏!

备注:内容来源于stack exchange,提问作者Noah Ross

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.13 19:00:28