Python问题。假设我有各种列表,就像这样,
[1, 5, 3, 1, 9, 10, 1, 20]
[1, 5]
[1, 2, 3, 1, 7, 10, 1, 2, 8, 21]
[1, 5, 6, 4, 0, 16, 1, 5, 6, 4, 0, 16]
这些数字代表体育比赛的得分,其中团队 1 是列表的前半部分,团队 2 是列表的后半部分。列表前半部分的最后一个数字(第 1 队得分)始终是比赛总分。列表上半部分倒数第二个数字始终是比赛加时赛得分。列表中的第一项是第一节的得分。列表中的第二项是第二节的得分。等等。例如,[1,5] 表示团队 1 的总得分为 1,团队 2 的总得分为 5。再例如,[1,5,3,9,9,10,1, 20]表示1队第一节得1分,第二节得5分,加时赛得3分,共9分,2队第一节得9分,第二节得10分,1分加时赛,总分20分。
我想创建一个函数,将列表中的这些数字粘贴到字典中,并且只有在列表中存在值时,它才应该填充字典键。
score['sec_away_team_1'], score['sec_away_team_2'], score['sec_away_team_3'], score['sec_away_team_4'], score['sec_away_team_ot'], score['sec_away_team_total'],
score['sec_home_team_1'], score['sec_home_team_2'], score['sec_home_team_3'], score['sec_home_team_4'], score['sec_home_team_ot'], score['sec_home_team_total']
一种方法是创建一个包含大量 if 语句的函数,如果我知道列表有多长,我可以针对如何解包列表执行不同的方案,但由于我将解包列表各种大小我认为制作这么多 if 语句会很难看...如何使用通用函数来完成此操作,该函数要么从列表中生成项目,要么使用它们并将它们弹出,或者以其他方式完成?
最佳答案
这个函数可以实现你想要的功能:
def scores_to_dict(scores):
d = {}
team_1 = ('team_1', scores[:len(scores)/2])
team_2 = ('team_2', scores[len(scores)/2:])
teams = [team_1, team_2]
for team, scores in teams:
for idx, score in enumerate(reversed(scores)):
if idx == 0:
d['%s_total' % team] = score
elif idx == 1:
d['%s_overtime' % team] = score
else:
d['%s_round_%s' % (team, len(scores)-idx)] = score
return d
测试它:
scores = [[1, 5, 3, 1, 9, 10, 1, 20],
[1,5],
[1, 2, 3, 1, 7, 10, 1, 2, 8, 21],
[1, 5, 6, 4, 0, 16, 1, 5, 6, 4, 0, 16]]
from pprint import pprint
for score in scores:
print score
pprint(scores_to_dict(score))
print '--'
输出:
>>>
[1, 5, 3, 1, 9, 10, 1, 20]
{'team_1_overtime': 3,
'team_1_round_1': 1,
'team_1_round_2': 5,
'team_1_total': 1,
'team_2_overtime': 1,
'team_2_round_1': 9,
'team_2_round_2': 10,
'team_2_total': 20}
--
[1, 5]
{'team_1_total': 1, 'team_2_total': 5}
--
[1, 2, 3, 1, 7, 10, 1, 2, 8, 21]
{'team_1_overtime': 1,
'team_1_round_1': 1,
'team_1_round_2': 2,
'team_1_round_3': 3,
'team_1_total': 7,
'team_2_overtime': 8,
'team_2_round_1': 10,
'team_2_round_2': 1,
'team_2_round_3': 2,
'team_2_total': 21}
--
[1, 5, 6, 4, 0, 16, 1, 5, 6, 4, 0, 16]
{'team_1_overtime': 0,
'team_1_round_1': 1,
'team_1_round_2': 5,
'team_1_round_3': 6,
'team_1_round_4': 4,
'team_1_total': 16,
'team_2_overtime': 0,
'team_2_round_1': 1,
'team_2_round_2': 5,
'team_2_round_3': 6,
'team_2_round_4': 4,
'team_2_total': 16}
--
关于python - 从不同列表动态构建字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19973336/