python - Python 3:如何使用用户输入从字典内列表中的值创建列表(或字典)?
问题描述
如果我使用用户输入从字典中的列表创建列表/字典,是否有可能?
E.g.
in the dictionary: {'fruits', 'veggies', 'drinks'}
every key has list: fruits = ['apple','manggo']
every value has a list (or maybe dict): apple = ['stock':30, 'amount':10]
到目前为止,我能够在字典中创建一个列表,但我无法从 list 中的每个值创建一个新列表apple = ['stock':30]
。
我的代码
class Inventory:
def __init__(self):
self.dict_inv = dict()
self.count_inv = int(input("Enter the number of inventories: "))
for count in range(self.count_inv):
name_inv = str(input("Enter Inventory #%d: " % (count+1)))
self.dict_inv[name_inv] = count
self.dict_inv[name_inv] = []
for name_inv in self.dict_inv:
max_item = int(input("How many items in {} " .format(name_inv)))
for count in range(max_item):
name_item = str(input("Enter item #%d: " % (count+1)))
self.dict_inv[name_inv].append(name_item)
self.dict_inv[name_inv[name_item]] = [] # <-- ERROR
# PRINTS EVERYTHING
for key in self.dict_inv.keys():
if type(self.dict_inv[key]) is list:
print("{} is a list" .format(key))
print("items in {} are {}" .format(key, self.dict_inv[key]))
Inventory()
解决方案
不确定您是否需要为此创建一个类。这会完成你想要做的事情吗?
# define a generator that ask the user to enter things until they quit.
def ask(thing):
user_input = 'x'
while user_input != 'quit':
user_input = input("Enter %s or 'quit' to stop: " % (thing))
if user_input != 'quit':
yield(user_input)
# use list comprehension to create inventory
inventory = [{c: [ {i: int(input("Enter stock: "))} for i in ask("item")]} for c in ask("category")]
# voila!
print( inventory )
以下是上述代码执行时发生的情况:
$ python3 inventory.py
Enter category or 'quit' to stop: fruit
Enter item or 'quit' to stop: apples
Enter stock: 45
Enter item or 'quit' to stop: bananas
Enter stock: 23
Enter item or 'quit' to stop: berries
Enter stock: 47
Enter item or 'quit' to stop: quit
Enter category or 'quit' to stop: cars
Enter item or 'quit' to stop: fords
Enter stock: 4
Enter item or 'quit' to stop: toyotas
Enter stock: 7
Enter item or 'quit' to stop: quit
Enter category or 'quit' to stop: quit
[{'fruit': [{'apples': 45}, {'bananas': 23}, {'berries': 47}]}, {'cars': [{'fords': 4}, {'toyotas': 7}]}]
我想如果你愿意的话,你可以把它带进课堂。
推荐阅读
- java - 如何在 Swing 的文本区域中设置语言?
- angular - 如何以角度使用 ArcGis ESRI 地图
- php - 错误在哪里?我想添加用户评论,它给了我错误
- authentication - Keycloak Action Tokens:当用户请求多个操作时如何使用户先前的操作无效(例如重置密码)
- node.js - 尝试在 POST 请求中使用 Google Speech Cloud 时出现 ReadFileSync 错误
- r - 使用管道中的 ifelse 条件修改某些值
- graph - AQL 和图遍历:产品推荐示例
- python-3.x - 我有一个查询,在执行以下代码时,我收到类型错误“Int object is not iterable”
- javascript - 如何使用 fetch 从 Flask 获取 POST 数据
- php - 使用PHP的随机可变长度bigint(8)数?