代码之家  ›  专栏  ›  技术社区  ›  Roman

python中的元组和列表排列

  •  -4
  • Roman  · 技术社区  · 10 年前

    因此,这四个“团队”完成了“目标”的总数:

    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 连续5个进球(5-10个) W 所以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
    

    有更简单的方法吗?

    1 回复  |  直到 10 年前
        1
  •  4
  •   Bharel    10 年前

    这是我认为最有效的方式:

    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]