Python Forum
Newbie question for sorting named tuple list - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Newbie question for sorting named tuple list (/thread-6870.html)



Newbie question for sorting named tuple list - zydjohn - Dec-11-2017

Hello:
I have a simple question, the following is my code:
import collections
Person = collections.namedtuple('Person', ['Name', 'Age', 'Height', 'Weight'])

person1 = Person(name='Bob', Age = 55, Height = 165, Weight = 70)
person2 = Person(name='Doe', Age = 45, Height = 185, Weight = 90)
person3 = Person(name='John', Age = 50, Height = 175, Weight = 85)
people = []
people.append(person1)
people.append(person2)
people.append(person3)
I want to sort the tuple list by the following 3 ways:
1. Sort by the Age, and print the person with the max/min age
2. Sort by the Height, and print the person with the max/min height
3. Sort by the Weight, and print the person with the max/min weight
How I can code this?
A furuther question: if you think other data type, not the named tuple could be better for my question, please
also advice and show me your code. I will use this kind of sort quite often in my program, so I wish a good
performance solution.
Please advise,
Thanks,


RE: Newbie question for sorting named tuple list - ODIS - Dec-11-2017

Python list object has built-in function for sorting. You can create function sort_people for your case like this way:

import collections

Person = collections.namedtuple('Person', ['Name', 'Age', 'Height', 'Weight'])

person1 = Person(Name='Bob', Age=55, Height=165, Weight=70)
person2 = Person(Name='Doe', Age=45, Height=185, Weight=90)
person3 = Person(Name='John', Age=50, Height=175, Weight=85)
people = [person1, person2, person3]


def sort_people(people, attribute, reverse=False):
    people.sort(key=lambda x: getattr(x, attribute), reverse=reverse)

# order by age
sort_people(people, "Age")

print(str(people))
If you'll want to reverse ordering, just put True as a third parameter into the function.


RE: Newbie question for sorting named tuple list - Larz60+ - Dec-11-2017

If you want to use tuples, see:
https://stackoverflow.com/questions/12087905/pythonic-way-to-sorting-list-of-namedtuples-by-field-name

however, consider using a dictionary:
debug = True

people = {
    'bob': {'Name': 'Bob', 'Age': 55, 'Height': 165, 'Weight': 70},
    'doe': {'Name': 'Doe', 'Age': 45, 'Height': 185, 'Weight': 90},
    'john': {'Name': 'John', 'Age': 50, 'Height': 175, 'Weight': 85}
}

max_age = [None, 0]
max_height = [None, 0]
max_weight = [None, 0]

for person, values in people.items():
    if values['Age'] > max_age[1]:
        max_age[0] = values['Name']
        max_age[1] = values['Age']
    if values['Height'] > max_height[1]:
        max_height[0] = values['Name']
        max_height[1] = values['Height']
    if values['Weight'] > max_weight[1]:
        max_weight[0] = values['Name']
        max_weight[1] = values['Weight']

print(f'{max_age[0]} is the oldest at {max_age[1]} years.')
print(f'{max_height[0]} is the tallest at {max_height[1]} inches.')
print(f'{max_weight[0]} is the heaviest at {max_weight[1]} lbs.')

# if you are not using python 3.6, replace above with:
# print('{} is the oldest at {} years.'.format(max_age[0], max_age[1]))
# print('{} is the tallest at {} inches.'.format(max_height[0], max_height[1]))
# print('{} is the heaviest at {} lbs.'.format(max_weight[0], max_weight[1]))
results:
Output:
Bob is the oldest at 55 years. Doe is the tallest at 185 inches. Doe is the heaviest at 90 lbs.



RE: Newbie question for sorting named tuple list - zydjohn - Dec-11-2017

(Dec-11-2017, 09:12 PM)ODIS Wrote: Python list object has built-in function for sorting. You can create function sort_people for your case like this way:

import collections

Person = collections.namedtuple('Person', ['Name', 'Age', 'Height', 'Weight'])

person1 = Person(Name='Bob', Age=55, Height=165, Weight=70)
person2 = Person(Name='Doe', Age=45, Height=185, Weight=90)
person3 = Person(Name='John', Age=50, Height=175, Weight=85)
people = [person1, person2, person3]


def sort_people(people, attribute, reverse=False):
    people.sort(key=lambda x: getattr(x, attribute), reverse=reverse)

# order by age
sort_people(people, "Age")

print(str(people))
If you'll want to reverse ordering, just put True as a third parameter into the function.

Good, your code works.
Thanks!