从不同列表动态生成字典

2024-03-29 09:40:45 发布

您现在位置:Python中文网/ 问答频道 /正文

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队得分)始终是比赛总数。上半场的倒数第二总是加时赛得分。第一项是第一节课的分数。第二项是第二节的分数。以此类推,[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语句会很难看…如何用一个生成项的泛型函数来实现呢从列表中,或使用它们并弹出,或其他方式?你知道吗


Tags: 方法函数home列表if字典数字sec
1条回答
网友
1楼 · 发布于 2024-03-29 09:40:45

此函数满足您的要求:

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}
 

相关问题 更多 >