从某种逻辑制作字典

时间:2016-02-18 18:55:04

标签: python

球队'A','B'和'C'分别连续进球12次,1次和9次。

teams = ['A','B','C']

goals = [12,1,9]

哪支队伍取得了第5个进球?答案是团队'A'。 哪支队伍取得了第13个进球?答案是团队'B'。 哪支球队做了第21个进球?答案是团队'C'。

我想制作团队与目标号码的字典。 @Kevin的回答很好。

dict(enumerate([t for t,g in zip(teams, goals) for _ in range(g)], 1))

然后,给定列表是[5,13,​​21]。如何获得列表:['A','B','C'] ??

2 个答案:

答案 0 :(得分:1)

goaldict = {}
goal_num = 1
for position,team in enumerate(teams):
    for goal in range(0, goals[position]):
        goaldict[goal_num] = team
        goal_num = goal_num + 1

答案 1 :(得分:1)

>>> teams = ['A','B','C']
>>> goals = [12,1,9]
>>> d = dict(enumerate([t for t,g in zip(teams, goals) for _ in range(g)], 1))
>>> d[5]
'A'
>>> d[13]
'B'
>>> d[21]
'C'

这大致相当于:

d = {}
count = 1
for team, goal in zip(teams, goals):
    for i in range(goal):
        d[count] = team
        count += 1