通过迭代分离列表中的列表

时间:2014-11-05 02:48:39

标签: python list

首先,这是一项家庭作业,但我现在已经工作了一个星期,并没有取得很大进展。我的这个功能的目标是获取一个列表列表(每个列表包含有关足球运动员的数据),并根据球员所属的球队分开列表。我还想把每个球员的数据加起来,这样我最终得到每个球队的一个列表,其中包含所有球员的统计数据。

这是我到目前为止的代码。我目前遇到的问题是,有些团队每次都会打印多次不同的数据。否则它似乎工作正常。此外,我们对我们施加了限制,我们不允许使用类。

def TopRushingTeam2010(team_info_2010): #running into trouble calculating the rusher rating for each team, it also prints out the same team multiple times but with different stats. And just not getting the right numbers and order. 
    total_yards = 0
    total_TD = 0
    total_rush = 0
    total_fum = 0
    #works mostly, but is returning some teams twice, with different stats each time, which
    #should not be happening. so... yeah maybe fix that?
    for item in team_info_2010:
        team = item[0]
        total_yards = item[2]
        total_TD = item[3]
        total_rush = item[1]
        total_fum = item[4]
        new_team_info_2010.append([team, total_yards, total_TD, total_rush, total_fum])

        for other_item in team_info_2010:
            if other_item[0] == team:
                new_team_info_2010.remove([team, total_yards, total_TD, total_rush, total_fum])
                total_yards = total_yards + other_item[2]
                total_TD = total_TD + other_item[3]
                total_rush = total_rush + other_item[1]
                total_fum = total_fum + other_item[4]
                new_team_info_2010.append([team, total_yards, total_TD, total_rush, total_fum])

关于我应该向哪个方向前进的任何帮助或提示,或者我是否朝着正确的方向前进?

1 个答案:

答案 0 :(得分:1)

一个可能的问题是,当您在列表中进行迭代时,您将从team_info_2010中删除。尝试删除该行代码。我没有看到你想要从team_info_2010删除的明确原因,并且当你在迭代它时修改一个对象时,行为通常是未定义的。更具体地说,尝试删除以下代码行:

team_info_2010.remove(item)