显示匹配用户输入值的列表条目

我是 python 3 的新手,正在创建一个收集程序,它由不同类型的项目组成。我在构建代码行以按类别显示项目和删除条目时遇到问题。我目前正在尝试创建一个选项,用户可以在其中输入类型(例如电话),列表将显示所有已添加并存储为 item_type 中电话的列表条目。


我写了这段代码,但 Show category & Delete item 部分不起作用。有人可以帮我理解代码公式有什么问题吗:


def show_items():

    print("{0:3}\t{1:10}\t{2:10}\t{3:10}".format("ID", "Item", "Date added", 'Date manufactured'))

    for i in Item.py_collection_list:

        print("{0:03d}\t{1:10}\t{2:10}\t{3:10}".format(i.get_id(), i.item_name, i.date_add, i.dom))

    response = input('Press [x] to go back to main menu or press [c] to view items by type ')

    if response == 'c':

        show_category()



def show_category():

    item_types = {"Computer": [], "Camera": [], "Phone": [], "Video Player": []}

    print()

    print('View items by type \nComputer | Camera | Phone | Video Player > ')

    response = input('Type> ')

    if response in item_types:

        print(item_types[response])


芜湖不芜
浏览 88回答 4
4回答

MM们

在您最初的问题中,您的主要障碍是Item.py_collection_list根据用户输入返回内部值的分类列表。查看您的实现,Item您似乎没有在类本身内部进行分类,因此当您想要输出值时,您必须自己对类型进行分类。我已经简化了您的代码以向您展示我将如何解决该问题:import randomclass Item:    py_collection_list = []    def __init__(self, item_type, item_value):        self.item_type = item_type        self.item_value = item_value        Item.py_collection_list.append(self)    # To make it easier for us to represent the values inside of the categories.    def __repr__(self):        return f"Item(item_type='{self.item_type}', item_value={self.item_value})"    # We make this a classmethod because we want to be able to call it using the class, aswell as the instances.    @classmethod    def show_category(cls):        # Here we dynamically create a dictionary that contans all the values inside of Item        # which are sorted by their types.        item_types = {}        for item in Item.py_collection_list:            item_types.setdefault(item.item_type, []).append(item)        # Write all available categories        print("Available Categories:")        print(" | ".join(i for i in item_types))        print("Please choose a category to show:")        choice = input("> ")        # Try to go through all the values of the dictionary and give back values.        try:            for item in item_types[choice.strip()]:                print(item)        except KeyError:            print(f"Error: '{choice}' is not a valid category!")# Lets create some random entries.categories = ["Computer","Camera", "Phone", "Video Player"]for i in range(100):    Item(item_type=random.choice(categories), item_value=round(random.uniform(0.0, 10.0), 2))Item.show_category()在上面的代码中,我将您的函数更改show_category为类方法 if Item。这使得我们可以在我们导入的每个程序中调用它Item。我还创建了一个__repr__of,Item以便我们可以更轻松地可视化每个值。这是我试运行上述代码之一的输出:Available Categories:Camera | Video Player | Phone | ComputerPlease choose a category to show:> PhoneItem(item_type='Phone', item_value=7.3)Item(item_type='Phone', item_value=2.34)Item(item_type='Phone', item_value=0.39)Item(item_type='Phone', item_value=0.03)Item(item_type='Phone', item_value=5.03)Item(item_type='Phone', item_value=6.72)Item(item_type='Phone', item_value=6.15)Item(item_type='Phone', item_value=3.33)Item(item_type='Phone', item_value=0.12)Item(item_type='Phone', item_value=0.63)Item(item_type='Phone', item_value=9.2)Item(item_type='Phone', item_value=2.99)Item(item_type='Phone', item_value=0.06)Item(item_type='Phone', item_value=9.25)Item(item_type='Phone', item_value=6.5)Item(item_type='Phone', item_value=5.51)Item(item_type='Phone', item_value=2.47)Item(item_type='Phone', item_value=4.4)Item(item_type='Phone', item_value=3.8)因为自 Python 3.6+ 以来,字典默认排序,类别的顺序将是随机的,因为它基于创建它的列表中首次出现的顺序。

千万里不及你

我不确定你想用Item.py_collection_list. 解决这个问题的一种更简单的方法是使用字典。就像是:def show_category():    all_items = {"Phone":["iPhone","OtherBrand0","OtherBrand1"], "Computer":["Asus","MSI","OtherBrand"]} # add {type: [list of products]}    print()    print('View items by type \nComputer | Camera | Phone | Video Player > ')    response = input('Type> ')    if response in all_items.keys():        print(all_items[response]) # or whatever

守着一只汪

假设您有一个包含所有条目的列表作为字典,其中一个键是"item_type",那么简单的列表理解就可以完成这项工作。entries = [entry for entry in allEntries if entry["item_type"]==response]这相当于写下面的entries = []for entry in allEntries:  if entry["item_type"] == response:    matches.append(c)

LEATH

这似乎有效:            def show_items():                print('View items by type \nComputer | Camera | Phone | Video Player ')                type_selection = input('Type> ')                print("{0:3}\t{1:20}\t{2:10}\t{3:10}".format("ID", "Item", "Date added", "Date manufactured"))                for i in Item.py_collection_list:                    if type_selection == i.item_type:                        print("{0:03d}\t{1:20}\t{2:10}\t{3:10}".format(i.get_id(), i.item_name, i.date_add, i.dom))
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python