开发者

Python csv: finding out rows with biggest values

开发者 https://www.devze.com 2023-02-13 23:17 出处:网络
I must be missing something, but I have trouble with finding out the biggest values and printing them using the csv.DictReader() function.

I must be missing something, but I have trouble with finding out the biggest values and printing them using the csv.DictReader() function.

The csv file is something like (I have cut the fields as well as rows because the rows are too wide for this format):

traverse;damage;hull_front;turret_back;penetration;full_name;tier;hull_back;turret_sides;type;hull_sides;turret_front
38;30;18;16;32;Light Tank MS-1;1;16;16;Light Tank;16;18
40;30;13;13;32;Light Tank BT-2;2;13;13;Light Tank;13;15
55;36;15;15;34;Light Tank T-26;2;15;15;Light Tank;15;15

(Hope I got all the fields, I had to use cut with the original file.)

I read this file with

tanks = csv.DictReader(open('tanks.csv', 'r'), delimiter = ';')

but when I try to found out e.g. which row has the biggest value in which column, I seem unable to read through the dictionary. My attempt looks like this:

def top_values(tanks):
  tank = list(itertools.islice(tanks,1,2))

  best_tanks = dict({'turret_front':tank, 'turret_sides':tank, 'turret_back':tank, 
                   'hull_front':tank, 'hull_sides':tank, 'hull_back':tank,
                   'penetration':tank, 'damage':tank, 'traverse':tank})

  fields = ['turret_front', 'turret_sides', 'turret_back', 
          'hull_front', 'hull_sides', 'hull_back',
          'penetration', 'damage', 'traverse']

  for tank in tanks:
      for field in fields:
        if tank[field] > best_tanks[field][field]:
            best_tanks[field] = tank

  print "Best tanks by values:\n"
  for field in fields:
    tank = best_tanks[field] 
    print field + ": " + tank['full_name'] + "(" + tank[field] + ")" 

But I get

Traceback (most recent call last):
File "./wotalyzer.py", line 102, in <module>
main(sys.argv[1:])
File "./wotalyzer.py",开发者_运维问答 line 98, in main
top_values(tanks)
File "./wotalyzer.py", line 44, in top_values
print field + ": " + tank['full_name'] + "(" + tank[field] + ")" 
TypeError: list indices must be integers, not str

How can I accomplish this? I want to do it like this to make it easy to add new fields.


In tank = list(itertools.islice(tanks,1,2)) you define tank as a list.

best_tanks is a dict with the values being the list tank.

In your if you replace the lists in best_tanks with the variable tank that now is a dict, so its ok to later use best_tanks[field][field].

But if the if if is not executed, the element in best_tanks will still have a list, resulting in best_tanks[field] being a list, which will result in the error TypeError: list indices must be integers, not str when you try to access the element with the string field

0

精彩评论

暂无评论...
验证码 换一张
取 消