我有一个编码挑战要求我创建一个逻辑,将一个字典列表分成三个新的dicts列表。新名单需要拥有相同数量的有经验和缺乏经验的人员。原始列表中有经验丰富且经验不足的人员。我不知道如何形成这个挑战的逻辑。这是一个缩短版本:
mylist = [
{'name': 'Jade', 'height': 64, 'experience': 'n'},
{'name': 'Diego', 'height': 60, 'experience': 'y'},
{'name': 'Twee', 'height': 70, 'experience': 'n'},
{'name': 'Wence', 'height': 72, 'experience': 'y'},
{'name': 'Shubha', 'height': 65, 'experience': 'y'},
{'name': 'Taylor', 'height': 68, 'experience': 'n'}
]
新的决策需要有相同数量的有经验和缺乏经验的人员:
newlist_1 = [
{'name': 'Diego', 'height': 60, 'experience': 'y'},
{'name': 'Jade', 'height': 64, 'experience': 'n'},
]
newlist_2 = [
{'name': 'Wence', 'height': 72, 'experience': 'y'},
{'name': 'Twee', 'height': 70, 'experience': 'n'},
]
newlist_3 = [
{'name': 'Shubha', 'height': 65, 'experience': 'y'},
{'name': 'Taylor', 'height': 68, 'experience': 'n'}
]
我保留原始列表,因此最终需要总共有四个集合。
答案 0 :(得分:1)
你可以有2个列表 - 一个有经验,一个没有经验,可以从中构建你需要的任何列表,如:
experienced = [worker for worker in mylist if 'y' == worker['experience']]
inexperienced = [worker for worker in mylist if 'n' == worker['experience']]
list1, list2, list3 = map(list, zip(experienced, inexperienced))
答案 1 :(得分:0)
尝试将词典列表切成三个单独的列表
list1 = mylist[0:2]
list2 = mylist[2:4]
list3 = mylist[4:6]
答案 2 :(得分:0)
def make_teams(my_list):
# divide the member list in two
experienced = list()
novice = list()
for record in my_list:
if record.get('experience') in ['Y','y']:
experienced.append(record)
else:
novice.append(record)
# stitch the two lists together as a list of tuples
teams = zip(experienced, novice)
# build a dictionary result starting with the member list
results={
'members':my_list
}
# update results with each team
for i in range(0,len(teams)):
results.update(
{'newlist_%s'%(i+1):list(teams[i])})
return results
将产生以下内容......
from pprint import pprint
pprint(make_teams(mylist))
{'members': [{'experience': 'n', 'height': 64, 'name': 'Jade'},
{'experience': 'y', 'height': 60, 'name': 'Diego'},
{'experience': 'n', 'height': 70, 'name': 'Twee'},
{'experience': 'y', 'height': 72, 'name': 'Wence'},
{'experience': 'y', 'height': 65, 'name': 'Shubha'},
{'experience': 'n', 'height': 68, 'name': 'Taylor'}],
'newlist_1': [{'experience': 'y', 'height': 60, 'name': 'Diego'},
{'experience': 'n', 'height': 64, 'name': 'Jade'}],
'newlist_2': [{'experience': 'y', 'height': 72, 'name': 'Wence'},
{'experience': 'n', 'height': 70, 'name': 'Twee'}],
'newlist_3': [{'experience': 'y', 'height': 65, 'name': 'Shubha'},
{'experience': 'n', 'height': 68, 'name': 'Taylor'}]}