为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

芜湖不芜 2022-12-20 16:14:10
我是 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])
查看完整描述

4 回答

?
MM们

TA贡献1886条经验 获得超2个赞

在您最初的问题中,您的主要障碍是Item.py_collection_list根据用户输入返回内部值的分类列表。


查看您的实现,Item您似乎没有在类本身内部进行分类,因此当您想要输出值时,您必须自己对类型进行分类。


我已经简化了您的代码以向您展示我将如何解决该问题:


import random


class 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 | Computer

Please choose a category to show:

> Phone

Item(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+ 以来,字典默认排序,类别的顺序将是随机的,因为它基于创建它的列表中首次出现的顺序。


查看完整回答
反对 回复 2022-12-20
?
千万里不及你

TA贡献1784条经验 获得超9个赞

我不确定你想用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


查看完整回答
反对 回复 2022-12-20
?
守着一只汪

TA贡献1872条经验 获得超3个赞

假设您有一个包含所有条目的列表作为字典,其中一个键是"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)


查看完整回答
反对 回复 2022-12-20
?
LEATH

TA贡献1936条经验 获得超6个赞

这似乎有效:


            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))



查看完整回答
反对 回复 2022-12-20
  • 4 回答
  • 0 关注
  • 80 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信