从16个团队中随机分配一个8个人中的一个

2024-10-01 17:41:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我试着把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)

Tags: import小组randomnickteampersonmartinrepublic
3条回答

这可以通过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}

结果就是一本字典。在

如果你想避免重复,你必须在列表上迭代。在

^{pr2}$

所以您要做的就是从teams中随机选择“元素的长度names”元素。在这种情况下,您应该使用^{}

>>> import random
>>> person = ['Name', 'Name', 'Name', 'Name', 'Name', 'Name', 'Name', 'Name']
>>> team = ['France', 'Switzerland', 'England', 'Slovakia', 'Germany', 'Ukraine', 'Spain', 'Czech Republic', 'Croatia', 'Italy', 'Republic of Ireland', 'Sweeden', 'Russia', 'Wales', 'Belgium']

>>> random.sample(team, len(person))
['Ukraine', 'Russia', 'England', 'Croatia', 'France', 'Spain', 'Italy', 'Wales']

the documentation

random.sample(population, k)

Return a k length list of unique elements chosen from the population sequence or set. Used for random sampling without replacement.

Returns a new list containing elements from the population while leaving the original population unchanged. The resulting list is in selection order so that all sub-slices will also be valid random samples. This allows raffle winners (the sample) to be partitioned into grand prize and second place winners (the subslices).


如果您想为每个人分配两个团队,我建议您^{}列表,team然后将列表分成两个大小的块,并将结果放入字典中:

^{pr2}$

使用^{}。在您的情况下,您可以有以下内容:

import random
names = ['Name1', 'Name2', 'Name3']
teams = ['France', 'Switzerland', 'England', 'Slovakia', 'Germany', 'Ukraine', 'Spain', 'Czech Republic', 'Croatia', 'Italy', 'Republic of Ireland', 'Sweeden', 'Russia', 'Wales', 'Belgium']
people = []

for name in names:
    people.append(random.choice(names), random.choice(teams))

people将是一个名称和一个团队的元组列表。在

相关问题 更多 >

    热门问题