将值附加到 python 中的列表

appending values to lists in python

我有以下代码。

rushingyards = 0
passingyards = 0
templist = []
combineddf = play.groupby(['GameCode','PlayType']).sum()
combineddf.to_csv('data/combined.csv', sep=',')
combineddff =pd.DataFrame.from_csv('data/combined.csv')
temp = {}
for row in combineddff.itertuples():
    if row[1] in ('RUSH', 'PASS'):
        temp['GameCode'] =  row[0]
        if row[1] == 'RUSH':
            temp['Rushingyards'] = row[10]
        else:
             temp['PassingYards'] = row[10]

    else:
        continue
    templist.append(temp)

我的合并 csv 的头部如下。

                 PlayType  PlayNumber  PeriodNumber  Clock  OffenseTeamCode  \
GameCode                                                                      
2047220131026     ATTEMPT         779            19   2220             1896   
2047220131026  FIELD_GOAL         351             9   1057              946   
2047220131026     KICKOFF        1244            32   4388             3316   
2047220131026        PASS        8200           204   6549            14730   
2047220131026     PENALTY        1148            29   1481             2372   

               DefenseTeamCode  OffensePoints  DefensePoints  Down  Distance  \
GameCode                                                                       
2047220131026             1896            142            123   NaN       NaN   
2047220131026              476             52             51    12        17   
2047220131026             2846            231            195   NaN       NaN   
2047220131026            23190           1131           1405   147       720   
2047220131026             2842            188            198    19        84   

               Spot  DriveNumber  DrivePlay  
GameCode                                     
2047220131026    24          NaN        NaN  
2047220131026    19           49          3  
2047220131026   850          NaN        NaN  
2047220131026  3719         1161         80  
2047220131026   514          164          1  

我必须检查游戏类型是 Rush 还是 pass 并相应地创建如下列表。

  Gamecode      rushing_yards   passingyards
  299004720130829     893          401 
  299004720130824     450          657 
  299004720130821     430          357

我无法正确附加值。每次运行时,它都会给出游戏代码、rushing_yards 和 passingyards 的所有相似值。请帮忙。

这是因为您要将引用附加到对象 temp。您基本上只是存储对同一对象的引用,这导致所有对象的值都相同。将您的临时字典放入 for 循环中,您应该会看到此问题的解决方案,因为它会在循环中的每次迭代时实例化一个新的字典对象。