Skip to main content
 首页 » 编程设计

python之从不同列表动态构建字典

2024年11月01日11artech

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} 
--