4 回答

TA貢獻(xiàn)1886條經(jīng)驗(yàn) 獲得超2個(gè)贊
在您最初的問(wèn)題中,您的主要障礙是Item.py_collection_list根據(jù)用戶(hù)輸入返回內(nèi)部值的分類(lèi)列表。
查看您的實(shí)現(xiàn),Item您似乎沒(méi)有在類(lèi)本身內(nèi)部進(jìn)行分類(lèi),因此當(dāng)您想要輸出值時(shí),您必須自己對(duì)類(lèi)型進(jìn)行分類(lèi)。
我已經(jīng)簡(jiǎn)化了您的代碼以向您展示我將如何解決該問(wèn)題:
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()
在上面的代碼中,我將您的函數(shù)更改show_category為類(lèi)方法 if Item。這使得我們可以在我們導(dǎo)入的每個(gè)程序中調(diào)用它Item。我還創(chuàng)建了一個(gè)__repr__of,Item以便我們可以更輕松地可視化每個(gè)值。
這是我試運(yùn)行上述代碼之一的輸出:
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)
因?yàn)樽?Python 3.6+ 以來(lái),字典默認(rèn)排序,類(lèi)別的順序?qū)⑹请S機(jī)的,因?yàn)樗趧?chuàng)建它的列表中首次出現(xiàn)的順序。

TA貢獻(xiàn)1784條經(jīng)驗(yàn) 獲得超9個(gè)贊
我不確定你想用Item.py_collection_list. 解決這個(gè)問(wèn)題的一種更簡(jiǎn)單的方法是使用字典。就像是:
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

TA貢獻(xiàn)1872條經(jīng)驗(yàn) 獲得超4個(gè)贊
假設(shè)您有一個(gè)包含所有條目的列表作為字典,其中一個(gè)鍵是"item_type",那么簡(jiǎn)單的列表理解就可以完成這項(xiàng)工作。
entries = [entry for entry in allEntries if entry["item_type"]==response]
這相當(dāng)于寫(xiě)下面的
entries = []
for entry in allEntries:
if entry["item_type"] == response:
matches.append(c)

TA貢獻(xiàn)1936條經(jīng)驗(yàn) 獲得超7個(gè)贊
這似乎有效:
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))
添加回答
舉報(bào)