我有4个部门:
# department 1, 2, 3, 4
departments = ['d1','d2','d3','d4']
每个部门有8个单位:
d1 = [1,2,3,4,5,6,7,8]
d2 = [1,2,3,4,5,6,7,8]
d3 = [1,2,3,4,5,6,7,8]
d4 = [1,2,3,4,5,6,7,8]
我需要创建工作组。
一个工作组由每个部门的 2 个单位组成,其中任何给定编号的单位只有一个人。总共 8 个单元,每个部门 2 个,必须包含 1 - 8 且单元号不能重复。
# Example Valid:
working_group_1 = ['d11', 'd12', 'd23', 'd24', 'd35', 'd36', 'd47', 'd48']
working_gorup_2 = ['d18', 'd17', 'd26', 'd25', 'd34', 'd33', 'd42', 'd41']
working_gorup_3 = ['d14', 'd18', 'd22', 'd26', 'd31', 'd35', 'd43', 'd47']
# each working group has 8 total individuals
# each working group has 2 individuals from each group
# each working group has 1 individual from each section 1-8
# Example Invalid:
working_group_4 = ['d12', 'd11', 'd23', 'd24', 'd35', 'd36', 'd47', 'd48']
# wg_4 is invalid because it is a copy of wg_1, where individuals from section 1, 2 are both assigned from the same department, just in a different order.
# This is not what I looking for, but might be close-ish
# The following snippet will give me all permutations
# e.g., ('d11', 'd12', 'd24', 'd27', 'd32', 'd34', 'd41', 'd46')
# The problem with this example is that, there are two individuals from unit 1
# - d11, d41 <- this is not allowed
import itertools
# Make the groups
groups = [[f'd{i+1}{j+1}' for j in range(8)] for i in range(4)]
lists = [list(itertools.combinations(groups[i],2)) for i in range(len(groups))]
#Generate list of all combinations, selecting 2 units from each department
all_combinations = []
for i in itertools.product(lists[0],lists[1],lists[2],lists[3]):
all_combinations.append(i[0]+i[1]+i[2]+i[3])
#Output all combinations
print(all_combinations)
任何帮助表示赞赏,在此先感谢。