亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

顯示匹配用戶輸入值的列表條目

顯示匹配用戶輸入值的列表條目

蕪湖不蕪 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條經驗 獲得超4個贊

假設您有一個包含所有條目的列表作為字典,其中一個鍵是"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條經驗 獲得超7個贊

這似乎有效:


            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 關注
  • 138 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號