Python 3.x 我想知道如何使用库统计数据访问对象列表中的数据,以获得平均值、中值和模式

Python 3.x 我想知道如何使用库统计数据访问对象列表中的数据,以获得平均值、中值和模式,python-3.x,class,object,statistics,Python 3.x,Class,Object,Statistics,到目前为止,我所拥有的: import statistics """This class is what captures and uses the values inputted into the class""" class Person: def __init__(self, name, age): self.name = name self.age = age def basic_stats(person_list): """ t

到目前为止,我所拥有的:

import statistics
"""This class is what captures and uses the values inputted into the class"""
class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

def basic_stats(person_list):
    """
    takes a list of person objects,
     and returns, mean, median, and mode of their ages
    """

    mean = statistics.mean(person_list.age)
    median = statistics.median(person_list.age)
    mode = statistics.mode(person_list.age)
    tuple = (mean, median, mode)

    return tuple
我正在这样测试它:

# test case:
p1 = Person("Kyoungmin", 73)
p2 = Person("Mercedes", 24)
p3 = Person("Avanika", 48)
p4 = Person("Marta", 24)
person_list = [p1, p2, p3, p4]
print(basic_stats(person_list))  # should print a tuple of three values
其目的是从每个对象p1、…、p4中提取年龄,并根据该信息计算平均值、中值和模式


谢谢您的时间,

我能看到的唯一问题是您需要将您的人员列表转换为年龄列表:

def basic_stats(person_list):
    ages = [person.age for person in person_list]

    mean = statistics.mean(ages)
    median = statistics.median(ages)
    mode = statistics.mode(ages)
    tuple = (mean, median, mode)

    return tuple

谢谢,我可以使用列表理解编写一个包含年龄值的新列表:new_list=[I.age for I in personal_list]