【问题标题】:Randomly Assign Value随机赋值
【发布时间】:2021-12-31 11:10:51
【问题描述】:

我正在开发一个程序,该程序应该将女性舞伴分配给男性舞伴。用户选择一个男舞者,程序应该随机分配一个女舞者,然后从原始列表中删除两个选择的舞者。在我的编码课上,我从来没有被教过如何像这样随机分配。这是我到目前为止的代码:

import random


maledancers = {"Maciek", "Marek", "Marcel", "Carson", "Brett", "Connor"}
femaledancers = {"Renata", "Karolina", "Maja", "Natalia", "Olivia", "Meghan"}



print("You will be pairing the male dancers with the female dancers.")
print("You will select one of the male dancers and it will get paired with a female dancer randomly")

dancer = input("Out of the male dancers, please select one to be paired: ")

if dancer not in maledancers:
    print("Your choice is not in the list of dancers, please re-enter a dancer from the list")
if dancer in maledancers:
    print("Great we will now randomly give " + dancer + " a partner to dance with")
if dancer.isdigit():
    print("The dancer can't have any numbers in their name. Try again please!")

如果有人对我可以在这里做什么有任何意见,我非常感谢任何帮助。如果您回答此问题,请显示代码更改。提前致谢!

【问题讨论】:

    标签: python list dictionary random computer-science


    【解决方案1】:

    应该这样做:

    import random
    
    
    maledancers = {"Maciek", "Marek", "Marcel", "Carson", "Brett", "Connor"}
    femaledancers = {"Renata", "Karolina", "Maja", "Natalia", "Olivia", "Meghan"}
    
    
    print("You will be pairing the male dancers with the female dancers.")
    print(
        "You will select one of the male dancers and it will get paired with a female dancer randomly"
    )
    
    for i in range(len(maledancers)):
    
        dancer = input("Out of the male dancers, please select one to be paired: ")
    
        if dancer not in maledancers:
            print(
                "Your choice is not in the list of dancers, please re-enter a dancer from the list"
            )
    
        if dancer in maledancers:
            print("Great we will now randomly give " + dancer + " a partner to dance with")
    
            # get a random female
            random_female = random.choice(list(femaledancers))
            # remove that female and male
            femaledancers.remove(random_female)
            maledancers.remove(dancer)
    
            # do wtevr u want with this female now
    
    
    

    我建议使用列表而不是集合,以避免在选择随机女性时频繁转换为列表。

    也不知道为什么你有最后一个 if 语句,关于 isdigit

    【讨论】:

    • 您好,感谢您的意见。最后一个 if 语句只是一些额外的东西,并不需要在那里。我还希望这个程序从舞者列表中删除 random_female 和用户输入,并将它们存储到另一个名为 dance_partners 的列表中。你能不能也帮我看看。我会尝试这样做,并再次评论我自己所做的事情。
    • 当然。您可以只使用.remove 方法从集合中删除一个值。编辑了帖子…
    • @MaciekB,你可以循环 len(dancers) 次数。编辑了帖子:)。尽管如此,我觉得你让我做你的功课:O
    • 你现在最好接受我的回答?
    • 哇。完成了作业却没有得到答案的功劳,真是太糟糕了!糟糕的举动@Hypnotix999
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-02-22
    • 2014-10-31
    • 1970-01-01
    • 1970-01-01
    • 2021-04-07
    • 2012-04-19
    • 1970-01-01
    相关资源
    最近更新 更多