This question already has answers here:
How to randomly select an item from a list?
                                
                                    (13个回答)
                                
                        
                                3年前关闭。
            
                    
我正在尝试将16个团队中的两个团队分配给8个人中的8个人,

这是我所拥有的:

import random
person = ['Ashton', 'Danny', 'Martin', 'Yves', 'Nick', 'Cormac', 'Thierry', 'Ciaran']
team = ['France', 'Switzerland', 'England', 'Slovakia', 'Germany', 'Ukraine', 'Spain', 'Czech Republic', 'Croatia', 'Italy', 'Republic of Ireland', 'Sweden', 'Russia', 'Wales', 'Belgium']
namesTeams = {}
for x in person:
    teamName = team[random.randint(0, len(team) -1)]
    namesTeams[x] = teamName
    team.remove(teamName)
print(namesTeams)

最佳答案

这可以用random.choice([List])完成

例:

import random

persons = ['Name', 'Name', 'Name', 'Name', 'Name', 'Name', 'Name', 'Name']

teams = ['France', 'Switzerland', 'England', 'Slovakia', 'Germany', 'Ukraine', 'Spain', 'Czech Republic', 'Croatia', 'Italy', 'Republic of Ireland', 'Sweeden', 'Russia', 'Wales', 'Belgium']

combinations = {p: random.choice(teams) for p in persons}


结果是一个字典。

如果要避免重复,则必须遍历列表。

combinations = {}
for p in persons:
    team = random.choice(teams)
    combinations[p] = team
    teams.remove(team)

关于python - 将16个小组中的随机小组分配给8个小组中的随机小组,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/37748417/

10-12 19:26