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