簡體   English   中英

帶對象python的排序列表-更有效的方法?

[英]Sorted list with objects python - more efficient way?

我正在用Python做一個初學者的任務,想知道是否有一種方法可以簡化此代碼,而不是在類中創建列表 需要對列表中的所有參數名稱,年齡,物種進行排序,反之亦然。

所以這可行,但是很丑:

def sortAnimal(llist):
    while True:
        print("\nChoose which parameter to sort: \n")
        print("1. Name\n2. Age\n3. Species\n")
        choice = int(input("Choice:"))
        print("\n")

        if choice == 1:
            print("{:7s} {:7s} {:7s} {:7s}".format("Name:", "Age:", "Species:", "Gender:"))
            sortedList = sorted(llist, key=lambda animal: animal.name)
            for obj in sortedList:
                print(obj)

            if input("\To reverse the list press enter. Otherwise press m + enter") == "":
                print("\n")
                print("{:7s} {:7s} {:7s} {:7s}".format("Name:", "Age:", "Species:", "Gender:"))
                sortedList = sorted(llist, key=lambda animal: animal.name, reverse= True)
                for obj in sortedList:
                    print(obj)
            else:
                pass

        elif choice == 2:
            # same code as option 1 but with animal.age
            pass

        elif choice == 3:
            #same code as option 1 but with animal.species
            pass

        if input("\To sort again press enter, back to menu press m + enter") == "":
            continue
        else:
            break

我以為是這樣的功能,但也沒有用:

def sortPrintAnimal(parameter, llist):
    while True:
        sortedList = sorted(llist, key=lambda animal: animal.parameter)
        print("{:7s} {:7s} {:7s} {:7s}".format("Name:", "Age:", "Species:", "Gender:"))
        for obj in sortedList:
            print(obj)

        if input("If you want to reverse the list press enter. Back to menu press m + enter: ") == "":
            # reversing the list
            pass
        else:
            break

使用getattr(obj,attr)意味着什么呢?

def sortAnimals(animals, key='name'):
    return sorted(animals, key=lambda animal: getattr(animal,key))


def attr(choice):
    return {
        1: "name",
        2: "age",
        3: "species"
    }[choice]


def display_animals(animals):
    print("{:7s} {:7s} {:7s} {:7s}".format("Name:", "Age:", "Species:", "Gender:"))
    for obj in animals:
        print(obj)


def main(animals):
    while True:
        print("\nChoose which parameter to sort: \n")
        print("1. Name\n2. Age\n3. Species\n")
        choice = int(input("Choice:"))
        try:
            sorted_animals = sortAnimals(animals, attr(choice))
        except KeyError:
            print("Invalid Choice {}".format(choice))
            continue
        display_animals(sorted_animals)

        if not input("To reverse the list press enter. Otherwise press m + enter"):
            sorted_animals.reverse()
            display_animals(sorted_animals)

        if input("To sort again press enter, back to menu press m + enter"):
            break

main(animals_list)

正如您提到的有效方式一樣 ,如果列表很大,則存儲排序后的列表以供將來使用會有所幫助

from collections import defaultdict
def main(animals):
    sort_map = defaultdict(dict)

    def _sorted_map(key, r_flag=False):
        if key not in sort_map:
            sort_map[key][False] = sortAnimals(animals, key)
        if r_flag and r_flag not in sort_map[key]:
            sort_map[key][True] = list(reversed(sort_map[key][False]))
        return sort_map[key][r_flag]


    while True:

        print("\nChoose which parameter to sort: \n")
        print("1. Name\n2. Age\n3. Species\n")
        choice = int(input("Choice:"))

        try:
            animal_attr = attr(choice)
        except KeyError:
            print("Invalid Choice {}".format(choice))
            continue

        sorted_animals = _sorted_map(animal_attr)
        display_animals(sorted_animals)

        if not input("To reverse the list press enter. Otherwise press m + enter"):
            sorted_animals = _sorted_map(animal_attr, True)
            display_animals(sorted_animals)

        if input("To sort again press enter, back to menu press m + enter"):
            break

您可以使用字典,其中是選項, 是要用作鍵的函數(lambda),例如:

def sortAnimal(llist):
    while True:
        print("\nChoose which parameter to sort: \n")
        print("1. Name\n2. Age\n3. Species\n")
        choice = int(input("Choice:"))
        print("\n")

        choices = {1: lambda animal: animal.name, 2: lambda animal: animal.age, 3: lambda animal: animal.species}

        print("{:7s} {:7s} {:7s} {:7s}".format("Name:", "Age:", "Species:", "Gender:"))
        sortedList = sorted(llist, key=choices[choice])
        for obj in sortedList:
            print(obj)

        if input("\To reverse the list press enter. Otherwise press m + enter") == "":
            print("\n")
            print("{:7s} {:7s} {:7s} {:7s}".format("Name:", "Age:", "Species:", "Gender:"))
            sortedList = sorted(llist, key=choices[choice], reverse=True)
            for obj in sortedList:
                print(obj)
            else:
                pass

        if input("\To sort again press enter, back to menu press m + enter") == "":
            continue
        else:
            break

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM