我需要选择2组,每组2名学生说的是同一语言,不要重复。每个学生仅出现一次。
我有此列表
import random
from itertools import permutations
seq = [['Sham','Arabic'],['Amina', 'Arabic'], ['Bill', 'French'], ['Qing','Hindi']]
我需要选择4组,每组2名学生说的是同一语言,不要重复。
我已经实现了此功能:
def group (x, y):
res=[]
#N = len(seq)
for i in range( y):
while len(res) < y:
res = random.sample(x,k=y)
while res[i][1] == res[i-1][1]:
return group(x,y)
return res
然后我应用这些条件以获得最终结果,一个学生必须只出现在一组中:
final = []
for i in range(2):
pick = group (seq, 2)
if pick in final or pick[::-1] in final:
group(seq, 2)
pass
for i in pick:
for j in i:
if j in final:
group(seq, 2)
pass
else:
final.append(pick)
print (final)
我仍然得到错误的结果,一位学生出现了不止一次。 预期结果:
[ [['Sham','Arabic'],['Qing','Hindi']],
[['Bill', 'French'], ['Amina', 'Arabic']] ]
但是我得到的(假两次):
[ [['Sham','Arabic'],['Qing','Hindi']],
[['Bill', 'French'], ['Sham','Arabic']] ]
答案 0 :(得分:0)
您没有正确应用条件。试试这个:
final = []
for i in range(4):
pick = group (seq, 2)
while pick in final or pick[::-1] in final:
pick = group(seq, 2)
final.append(pick)
print(final)
您需要继续选择,直到新的pick
不在final
中为止。这可以使用while循环来完成。
正如我在评论中提到的那样,不可能有四个组满足条件,但是如果您需要两个组(如您的预期输出)满足条件,那么这是您需要应用的附加条件:>
picked = []
final = []
for i in range(2):
pick = group (seq, 2)
while pick in final or pick[::-1] in final or any(p in picked for p in pick):
pick = group (seq, 2)
final.append(pick)
picked.extend(pick)
print(final)
您可以使用其他列表(picked
),其中包含到目前为止选择的学生语言对。然后继续挑选,直到新的群组picked
中没有配对为止。