天天看点

python最大值行_Python csv:找出具有最大值的行

我一定错过了一些东西,但是我在找出最大的值并使用csv.DictReader()函数打印它们时遇到了问题。

csv文件是类似的(我已经删除了字段以及行,因为这些格式的行太宽):

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(希望我得到了所有的领域,我不得不使用原始文件剪切。)

我读了这个文件

tanks = csv.DictReader(open('tanks.csv', 'r'), delimiter = ';')但是当我试图找出例如哪一行在哪个列中具有最大的价值,我似乎无法通过字典来阅读。我的尝试看起来像这样:

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] + ")"但我明白了

Traceback (most recent call last):

File "./wotalyzer.py", line 102, in

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我怎样才能做到这一点?我想这样做,以便轻松添加新字段。