更改排序键而不使用类外部的任何属性

问题描述 投票:0回答:1

我尝试使用“Person”类实现合并排序,但是我不能在此类之外使用“Person”的任何属性。我想根据“create_persons_list”函数中的 sort_key 值更改“mergesort”函数的关键参数 - 我使用 lambda 函数。我在 person_objects 中创建一个包含姓名、年龄、身高和体重的元组。因此,如果我想根据名称对列表进行排序,请将排序键设置为元组的索引 0。

import numpy as np
#import load_names
import enum
from merge_sort import mergesort



# NAMES is a list or array with common first names.
NAMES = ["Alice", "Bob", "Charlie", "David", "Eve", "Frank", "Grace", "Hank", "Ivy", "Jack"]  # Variables in the global namespace should be capitalized.


class Person():
    
    def __init__(self, name, age, height, weight):
        self._name = name
        self._age = age
        self._height = height
        self._weight = weight


    def __len__(self):
        return len(self.data)



    def __repr__(self):
        return f"{self._name}, {self._age} years, {self._height} cm, {self._weight} kg\n"

    def __eq__(self, other):
        return (self._age, self._height, self._weight) == (other._age, other._height, other._weight)

    def __lt__(self, other):
        return (self._age, self._height, self._weight) < (other._age, other._height, other._weight)

    def __le__(self, other):
        return (self._age, self._height, self._weight) <= (other._age, other._height, other._weight)

    def __gt__(self, other):
        return (self._age, self._height, self._weight) > (other._age, other._height, other._weight)

    def __ge__(self, other):
        return (self._age, self._height, self._weight) >= (other._age, other._height, other._weight)



    def __int__(self):
        return int(self._age)

    def __float__(self):
        return float(self._age)

    def __str__(self):
        return f"{self._name}, {self._age} years, {self._height} cm, {self._weight} kg"




def create_persons_list(n=10, sort_key='weight'):
    
    person_objects = [(Person(np.random.choice(NAMES), np.random.randint(18, 101), np.random.randint(150, 201), np.random.randint(45, 101))) for _ in range(n)]
    #print("po: ",person_objects[0])
    if sort_key == 'name':
        return mergesort(person_objects, key=lambda x: x[0])
    elif sort_key == 'age':
        return mergesort(person_objects, key=lambda x: x[1])
    elif sort_key == 'height':
        return mergesort(person_objects, key=lambda x: x[2])
    elif sort_key == 'weight':
        return mergesort(person_objects, key=lambda x: x[3])
    else:
        raise ValueError("Invalid sort_key. Supported values are 'name', 'age', 'height', and 'weight'.")


sorted_persons_by_name = create_persons_list(sort_key='name')
sorted_persons_by_age = create_persons_list(sort_key='age')
sorted_persons_by_height = create_persons_list(sort_key='height')
sorted_persons_by_weight = create_persons_list(sort_key='weight')

print("Sorted by name: \n")
print(sorted_persons_by_name)
print("Sorted by age: \n")
print(sorted_persons_by_age)
print("Sorted by height: \n")
print(sorted_persons_by_height)
print("Sorted by weight: \n")
print(sorted_persons_by_weight)


#print(create_persons_list())

如果我执行它,我会得到一个 TypeError,即“Person”对象不可订阅。是否可以在不使用“Person”类之外的任何属性的情况下实现我的想法?

python class mergesort
1个回答
0
投票

传递给 lambda 函数的

x
是一个 Person 对象,而不是一个元组。所以它应该是类似
key=lambda x: x._age
或任何合适的东西。

© www.soinside.com 2019 - 2024. All rights reserved.