目前,我的脚本采用一个csv名称列表,根据用户的偏好将它们随机分组
有多少组
或
每组有多少人
. 我的代码中有一个缺陷,它只对每个组的偶数个名称进行排序。例如,如果列表中有30个人,并且用户想要5个组,那么它将为每个组排序6个组。此外,如果列表中有33个名称,并且用户想要5个组,那么它仍然只对每个组排序6个,而忽略其余3个名称。
我是一个初级程序员,我正在寻找一些帮助来编辑我的代码,以便通过csv枚举并将所有名称添加到一个组中,即使名称总数是奇数(例如,组1-3每个有7个名称,组4&5每个有6个名称,等于所有33个名称)。
这是我当前的代码:
import csv
import random
import pprint
import sys
#import pandas as pd
with open(input('Enter file name: \n'),'r', encoding = 'Latin-1') as csvfile: # opens csv directory file
rdr = csv.reader(csvfile)
rdr = list(rdr)
def name_generator(lst): # generator that shuffles list of names
random.shuffle(lst)
return lst
shuf_lst = name_generator(rdr) # list of shuffled names
headcount = len(shuf_lst) # how many names in the list (will later be rsvp'd names only)
def group_size_generator():
final_dict2 = {} #initiated blank dictionary
gpsz = input('How many people per group? \n')
gpct = int(headcount) // int(gpsz) # number of people per group
for x in range(int(gpct)):
final_dict2['group{0}'.format(str(x+1))] = x + 1
if len(shuf_lst) != 0:
for k, v in final_dict2.items():
workinglist = []
for y in range(int(gpsz)):
workinglist.append(shuf_lst[0])
del shuf_lst[0]
final_dict2[k] = workinglist
pprint.pprint(final_dict2)
def group_number_generator():
final_dict1 = {} # initiated blank dictionary
gpct = input('How many groups? \n')
gpsz = int(headcount) // int(gpct) #number of of people per group
print(gpsz)
for x in range(int(gpct)): # initializes the dict with group identifiers
final_dict1['group{0}'.format(str(x + 1))] = x + 1
if len(shuf_lst) != 0: # condition that appends specified number of names per group to the groups in dict
for k, v in final_dict1.items():
workinglist = []
for y in range(int(gpsz)):
workinglist.append(shuf_lst[0])
del shuf_lst[0]
final_dict1[k] = workinglist
pprint.pprint(final_dict1)
def user(): #user input
user_input = input('Choose one: \n A.) How may people per group? \n B.) How many groups? \n')
for x in user_input:
if x == 'A' or x == 'a':
return(group_size_generator())
if x == 'B' or x == 'b':
return(group_number_generator())
else:
print('Error: Appropriate option not selected. Please try again.')
print(user())