Amy Rose Amy Rose - 15 days ago 7
Python Question

How to get the max/min value for multiple indices

I have a large dataset with multiple lines and want to return the largest value for

index[2]
out of all lines. So in the example below I want 20 to be returned. The following just prints the value at the index and not the maxima.

1,"Goroka",10,"Pacific"
2,"Madang",20,"Pacific"
3,"Mount Hagen",5,"Pacific"

for line in data.readlines():
splitLine = line.split(",") # Split line on ,
ID = splitLine[0]
name = splitLine[1]
no = splitLine[2]
ocean = splitLine[4]

print max(no)

Answer

Build the maximum as you go:

maxno = 0
for line in data.readlines():
    splitLine = line.split(",") # Split line on ,
    ID = splitLine[0]
    name = splitLine[1]
    no = splitLine[2]
    ocean = splitLine[4]
    if no > maxno:
        maxno = no

 print maxno