Skip to content Skip to sidebar Skip to footer

Python - Ordering Number Values In A List Containing Strings And Numbers

I have Created a list which contains all of the information from a scores file in python. The scores .txt file: Dan Danson,9,6,1 John Johnson,5,7,10 Mike Mikeson,10,7,6 I did this

Solution 1:

Using sorted with int as a key function:

>>> rows = [
...     ['Dan Danson', '1', '6', '9'],
...     ['John Johnson', '5', '7', '10'],
...     ['Mike Mikeson', '10', '7', '6'],
... ]
>>>
>>> rows = [row[:1] + sorted(row[1:], key=int, reverse=True) for row in rows]
>>> sorted(rows, key=lambda row: sum(map(int, row[1:])), reverse=True)
[['Mike Mikeson', '10', '7', '6'],
 ['John Johnson', '10', '7', '5'],
 ['Dan Danson', '9', '6', '1']]
  • sorted(row[1:], ..): separate number values and sort.
  • row[:1]: name as a list, alternatively you can use [row[0]]. Should be a list to be concatenated to a list of number strings.

Solution 2:

Using sorted and map to cast strings to ints:

>>>l = [['Dan Danson', '9', '6', '1'], ['John Johnson', '10', '7', '5'], ['Mike Mikeson', '10', '7', '6']]>>>for e in l:...print(e[0], *sorted(list(map(int, e[1:]))))...... 
Dan Danson 1 6 9
John Johnson 5 7 10
Mike Mikeson 6 7 10

Solution 3:

You can approach the problem this way as well. I first convert all grades into integer type so that I can keep my lambda function clean. I could have done the conversion in lambda function but it does not fancy me much.

You can see splitting the each problem into different module, gives re-usability.

test = [['Dan Danson', '1', '6', '9'], ["Karthikeyan", 10, 10, 10], ['John Johnson', '5', '7', '10'], ['Mike Mikeson', '10', '7', '6']]

defcovert_to_integer(test):
    """
    Coverting all grades into integer type
    """for outer_index, item inenumerate(test):
        for inner_index, element inenumerate(item[1:], 1):
            test[outer_index][inner_index] = int(element)
    return sorting_by_sum(test)

defsorting_by_sum(test):
    """
    Sorting the records by sum of the grades. 
    """returnsorted(test, key=lambda record: record[1]\
                                   + record[2] \
                                   + record[3], reverse=True)

if __name__ == "__main__":
    print covert_to_integer(test)

You can even use the sum method of list in lambda function. Like this:

returnsorted(test, key=lambda record: sum(record[1:])\
                                   ,reverse=True)

Post a Comment for "Python - Ordering Number Values In A List Containing Strings And Numbers"