user3077563
user3077563

Reputation: 3

Trouble using max(list)

Im trying to use max() func to find max value in given a list. Im creating a list for a given column from a txt file (representing a table, each line has a name and same amount of data columns). for example - John,M,53,175,8000 (name,. gender, age, height, salary) The problem is, I dont know if the column will contain numbers or strings. If the column contains integers, then it looks like this (for example): ['1','40','5','520','1025'] In that case, the max() func is comparing first digit and gives back a wrong value ('520'). Here is the relavant code - (Everything is within a class) First func. is returning a list of a give column. The second returns the name/names that has max value of the given column.

def get_column(self,colname):
    if colname not in self.columns:
        raise ValueError('Colname doesnt exists')
    col_indx = self.columns.index(colname)+1
    col_data = []   
    for i in range(len(self.names)):            
        col_data.append(self.data[i][col_indx])     
    return col_data 

def get_row_name_with_max_value(self,colname):
    if colname not in self.columns:
        raise ValueError('Colname doesnt exists')
    col_list = self.get_column(colname)
    max_val = max(col_list)
    counter = col_list.count(max_val)
    max_name = []
    k = -1
    for i in range(counter):
        index = col_list.index(max_val, k+1)
        max_name.append(self.data[index][0])
        k = index
    return ', '.join(max_name)

thanks alot!

Upvotes: 0

Views: 94

Answers (2)

georg
georg

Reputation: 214949

Check if your list consist only of numeric strings before calling max, if this is a case, use key=int:

def kmax(col):
    key = int if all(x.isdigit() for x in col) else str
    return max(col, key=key)

print kmax(['1','40','5','520','1025']) # 1025
print kmax(['foo','bar','40','baz']) # foo

Upvotes: 1

Zah
Zah

Reputation: 6804

You can use the key argument of the max() function to specify comparison as ints:

In [1]: l = [1,'2',3,'100']

In [2]: max(l, key = int)
Out[2]: '100'

Probably you want to apply int() to the output as well.

Upvotes: 3

Related Questions