利用 Python 构建不放回元素的组合,并筛选出满足组合多个组合条件的分组方式
利用的库:itertools
相关的函数:combinations(利用list生成组合)
完整拷贝list,copy模块,deepcopy
查询list中元素的下标:list.index(‘内容’)
对于存在元素重复的list,index函数不满足诉求,通过先构造下标组合,再利用下标去计算对应数组,最终筛选出符合条件的下标组合。
背景
1.已知16位数组orglist1至orglist6。
2.要求A 将数组内元素分为两组。
3.要求B 每组元素分成两小组后,两小组均需大于等于48,小于50。
4.要求C 分组结果需同时满足orglist1至orglist6的分组策略。
例如:如下分组,区分出AB两组的下标结果。
代码部分
from itertools import combinations
import copy
"""
参数1:待计算数组: origist
参数2:下标组合数组: resultlist
传出符合条件的新的下标数组
"""
def checklist(orglist, resultlist):
temp_index = []
for temp_i in resultlist:
# print("temp_i")
# print(temp_i) # temp_i 为下标数组 形如 (3, 4, 5, 6, 7, 8, 10, 11, 12, 13, 14, 15)
# 传入一个下标数组,计算对应的数据组之和
temp_check_sum = 0
for temp_k in temp_i:
temp_check_sum = temp_check_sum + orglist[temp_k]
# 求和结果判断
if 48 <= temp_check_sum < 50: # 业务规则,大于等于48,小于50
temp_index.append(temp_i) # 将满足情况的组合对应的下标存贮起来
# print(temp_j)
# print(temp_check_sum)
resultlist.clear()
resultlist = copy.deepcopy(temp_index)
print(resultlist)
return resultlist
list_org_1 = [13.50, 8.50, 6.67, 4.00, 4.00, 3.50, 2.00, 1.83, 3.00, 5.00, 2.33, 2.17, 1.33, 1.83, 19.17, 19.17]
list_org_2 = [15.00, 8.00, 6.00, 5.00, 5.00, 2.86, 2.29, 2.14, 1.57, 5.43, 2.71, 2.00, 1.43, 0.57, 18.86, 19.14]
list_org_3 = [13.50, 7.50, 5.50, 6.00, 6.00, 1.50, 0.75, 3.75, 3.75, 8.00, 6.00, 2.00, 1.50, 0.75, 14.00, 17.50]
list_org_4 = [12.00, 8.00, 6.00, 7.00, 9.00, 0.93, 1.71, 0.93, 0.43, 11.29, 1.36, 4.29, 0.64, 1.43, 12.00, 15.00]
list_org_5 = [12.00, 8.00, 6.00, 7.00, 9.86, 0.00, 0.86, 0.29, 0.29, 12.86, 0.29, 4.00, 0.57, 0.00, 14.00, 16.00]
list_org_6 = [12.95, 8.03, 6.05, 6.05, 7.32, 1.58, 1.61, 1.47, 1.37, 9.16, 2.05, 3.24, 0.97, 1.00, 14.97, 16.87]
list_index = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
result = [] # 下标结果,对应数据行数
for i in range(3, 13):
result.append(list(combinations(list_index, i)))
# print(result)
print("下标生成结束,开始筛选第1组---------------------------------------")
index = []
for i in result:
for j in i:
# print(j) j为下标数组 形如 (3, 4, 5, 6, 7, 8, 10, 11, 12, 13, 14, 15)
# 传入一个下标数组,计算对应的数据的序列的和
temp_sum = 0
for k in j:
temp_sum = temp_sum + list_org_1[k]
# 对下标对应的 数据组 求和
if 48 <= temp_sum < 50:
index.append(j)
# print(j)
# print(temp_sum)
result.clear()
result = copy.deepcopy(index)
print(result)
print("筛选2组数据---------------------------------------------------")
result = checklist(list_org_2, result)
print("筛选3组数据---------------------------------------------------")
result = checklist(list_org_3, result)
print("筛选4组数据---------------------------------------------------")
result = checklist(list_org_4, result)
print("筛选5组数据---------------------------------------------------")
result = checklist(list_org_5, result)
print("筛选6组数据---------------------------------------------------")
result = checklist(list_org_6, result)
print("筛选结束,符合条件的组合共:------------------------------------")
print(len(result))
备注:对于list中存在重复值的情况,index函数不适用,只能返回第一个查询到的索引值(下标)。