这些四队'因此做了“目标”的总数':
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
在W
之后连续5个目标(5-10),所以目标7是他们的,依此类推。
我试过但似乎很难:
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
有更简单的方法吗?
答案 0 :(得分:4)
这是我认为最有效的方式:
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]