使用Python随机配对列表中的项目

时间:2015-08-30 11:53:27

标签: python

我正努力在课堂上随机配对学生。这就是我想出的:

import random

students = ['Joe', 'Sam', 'Bob', 'Jill', 'Paul', 'Eric', 'Chai', 'Chris', 'Sui', 
'Matt', 'Leon', 'Nami', 'Leonard', 'Sai', 'Mike', 'Julie', 'Jim', 'Holly',
'Marge', 'Ed']

random.shuffle(students)

group1 = students[0:10]
group2 = students[10:]

combined = zip(group1, group2)

for first_student, second_student in combined:
    print str(first_student), "and", str(second_student)

但如果你还不知道学生人数,你会怎么做?关于如何改进这个的任何其他建议?

编辑:以下是包含多项建议的成品。我想在不导入itertools的情况下这样做。 (因为我想了解发生了什么。)

import random

students = ['Joe', 'Sam', 'Bob', 'Jill', 'Paul', 'Eric', 'Chai', 'Chris', 'Sui', 
'Matt', 'Leon', 'Nami', 'Leonard', 'Sai', 'Mike', 'Julie', 'Jim', 'Holly',
'Marge', 'Ed']

random.shuffle(students)

groups = zip(*[iter(students)]*2)

for first_student, second_student in groups:
    print str(first_student), "and", str(second_student)

2 个答案:

答案 0 :(得分:7)

您的解决方案通过将学生分成两组来限制可能的配对,并且每组只取一个。最好只在整个学生名单上进行一次洗牌,然后一次拿两个来进行配对。

import random

from itertools import izip_longest


def grouper(iterable, n, fillvalue=None):
    "Collect data into fixed-length chunks or blocks"
    # Taken from itertools recipes:
    # https://docs.python.org/2/library/itertools.html#recipes
    # grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx
    args = [iter(iterable)] * n
    return izip_longest(fillvalue=fillvalue, *args)


students = ['Joe', 'Sam', 'Bob', 'Jill', 'Paul', 'Eric', 'Chai', 'Chris',
            'Sui', 'Matt', 'Leon', 'Nami', 'Leonard', 'Sai', 'Mike',
            'Julie', 'Jim', 'Holly', 'Marge', 'Ed']

random.shuffle(students)

for first_student, second_student in grouper(students, 2):
    print str(first_student), "and", str(second_student)

答案 1 :(得分:1)

我遇到了同样的问题,并使用此代码来解决它。

import random

students_list_1 = ['Hadi', 'Farzad', 'Amirhossein', 'Yasaman']
students_list_2 = students_list_1.copy()

random.shuffle(students_list_1)
random.shuffle(students_list_2)

while len(students_list_2) > 0:
    if students_list_2[-1] == students_list_1[-1]:
        std2 = students_list_2.pop(0)
        std1 = students_list_1.pop()
        print(std1, '-', std2)
        students_list_1.remove(std2)
        students_list_2.remove(std1)
    else:
        std2 = students_list_2.pop()
        std1 = students_list_1.pop()
        print(std1, '-', std2)
        students_list_1.remove(std2)
        students_list_2.remove(std1)