我有一份包含产品,价格和数量的清单
[['apple', 'orange', 'banana'], [.50, .75, .20], [10,8,12]]
我正在尝试永久更改列表,方法是询问用户他们希望更新哪个产品,是否希望更新价格或数量,然后更新它们的选择方式
答案 0 :(得分:0)
idx = products[0].index(userInput)
if userInput_2 == 'price':
products[1][idx] = new value
if userInput_2 == 'quantity':
products[2][idx] = new value
答案 1 :(得分:0)
将用户输入分配给列表索引与通常将值分配给列表索引的方式没有区别。
products = [['apple', 'orange', 'banana'], [.50, .75, .20], [10, 8, 12]]
valid = False
while not valid:
userIn = input('Which product would you like to update? ')
if userIn in products[0]:
x = products[0].index(userIn)
valid = True
userIn2 = input('Would you like to update the quantity or price?')
if userIn2.lower() == 'price':
products[1][x] = int(input('Enter new value for price: '))
elif userIn2.lower() == 'quantity':
products[2][x] = int(input('Enter new value for quantity: '))
print(products)
答案 2 :(得分:0)
除非您/需要/使用列表进行练习,否则我认为这是错误的数据结构。
products = {
'apple': {'price': .50, 'quantity': 10},
'orange': {'price': .75, 'quantity': 8},
}
product_str = input(f'Which product would you like to update? ({list(products.keys())})')
try:
product = products[product_str]
except KeyError as err:
raise KeyError(f'Unknown product ({err})')
attrib_str = input(f'Which attribute would you like to update? ({list(products["orange"].keys())})')
try:
product[attrib_str] = float(input(f'Enter new value for {attrib_str}:'))
except KeyError as err:
raise KeyError(f'Unknown attribute ({attrib_str})')
以上内容仅仅是我的头脑,未经测试,但展示了这个想法。您还可以将值存储为索引列表或其他类似的东西,我只是喜欢这个简单的可读性和易于错误处理的案例。
答案 3 :(得分:0)
您最终可能希望扩展您的水果列表。以下解决方案通过将所有必需信息封装在dict
。
def update_fruits(lst, info):
fruit = lst[0].index(input('Which product would you like to update? ').lower())
column, tp = info[input('Would you like to update the quantity or price? ').lower()]
lst[column][fruit] = tp(input('What\'s the new values? '))
lst = [['apple', 'orange', 'banana'], [.50, .75, .20], [10, 8, 12]]
info = {'price': (1, float), 'quantity': (2, int)}
update_fruits(lst, info)
print(lst)
Which product would you like to update? banana
Would you like to update the quantity or price? price
What's the new values? 0.33
[['apple', 'orange', 'banana'], [0.5, 0.75, 0.33], [10, 8, 12]]
可以像这样动态添加水果。
for col, value in zip(lst, ['mango', 0.99, 5]):
col.append(value)
update_fruits(lst, info)
print(lst)
Which product would you like to update? mango
Would you like to update the quantity or price? quantity
What's the new values? 9
[['apple', 'orange', 'banana', 'mango'], [0.5, 0.75, 0.2, 0.99], [10, 8, 12, 9]]