Python Forum
Newbie question for sorting named tuple list
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Newbie question for sorting named tuple list
#1
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,
Reply
#2
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.
Reply
#3
If you want to use tuples, see:
https://stackoverflow.com/questions/1208...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.
Reply
#4
(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!
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  using > < for tuple , list,... akbarza 3 481 Feb-05-2024, 01:18 PM
Last Post: deanhystad
  How is pandas modifying all rows in an assignment - python-newbie question markm74 1 704 Nov-28-2023, 10:36 PM
Last Post: deanhystad
  newbie question - can't make code work tronic72 2 694 Oct-22-2023, 09:08 PM
Last Post: tronic72
Question mypy unable to analyse types of tuple elements in a list comprehension tomciodev 1 483 Oct-17-2023, 09:46 AM
Last Post: tomciodev
  Newbie question about switching between files - Python/Pycharm Busby222 3 609 Oct-15-2023, 03:16 PM
Last Post: deanhystad
  Change font in a list or tuple apffal 4 2,695 Jun-16-2023, 02:55 AM
Last Post: schriftartenio
  Newbie.... run for cover. OpenCV question Stevolution2023 2 978 Apr-12-2023, 12:57 PM
Last Post: Stevolution2023
  numpy newbie question bcwilly_ca 4 1,190 Feb-10-2023, 05:55 PM
Last Post: jefsummers
  List Sorting Problem ZZTurn 5 1,348 Sep-22-2022, 11:23 PM
Last Post: ZZTurn
  search a list or tuple for a specific type ot class Skaperen 8 1,945 Jul-22-2022, 10:29 PM
Last Post: Skaperen

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020