因此,这四个团队组成了“目标”总数:
teams = ['W', 'X', 'Y', 'Z']
goals = [4, 5, 1, 9]
现在,如何知道哪个团队遵循了目标?
given_goals = [3, 2, 7, 15]
预期答案应采用以下形式:
answers = [('W', (2, 3)),
('X', 7),
('Z', 15)]
W
连续取得了4个进球,因此第2个和第3个进球是他们的目标。然后X
在第7个目标之后创建5个连续目标(5-10)W
,依此类推。
我尝试过,但似乎很困难:
teams_ = [team for team, goal in zip(teams, goals) for g in range(goal)]
teams_goals = [teams_[g-1] for g in given_goals]
print teams_goals
有没有更简单的方法?
我认为这是最有效的方式:
import bisect
import itertools
teams = ['W', 'X', 'Y', 'Z']
goals = [4, 5, 1, 9]
# Create the max goal of each team
goal_ranges = itertools.accumulate(goals)
# Create sorted tuples of goals and teams (comes sorted because of accumulate)
ordered_teams = list(zip(goal_ranges, teams))
def get_team(goal_number):
# Get the leftmost occurence of the goal number, and extract the team from the tuple
return ordered_teams[bisect.bisect_left(ordered_teams, (goal_number,))][1]
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句