简体   繁体   English

尝试根据多个用户输入来修改列表

[英]Trying to modify a list based on multiple user inputs

I have a list of lists with products, price, and quantity 我有产品,价格和数量的清单清单

[['apple', 'orange', 'banana'], [.50, .75, .20], [10,8,12]]

I'm trying to permanently change the list based on asking the user which product they wish to update, if they wish to update the price or the quantity, and then update it how they choose 我试图根据询问用户他们想要更新的产品,是否要更新价格或数量,然后根据自己的选择来更新列表,来永久更改列表。

idx = products[0].index(userInput)
if userInput_2 == 'price':
    products[1][idx] = new value
if userInput_2 == 'quantity':
    products[2][idx] = new value

Assigning user input to a list index is not different from the way you normally assign value to a list index. 将用户输入分配给列表索引与通常将值分配给列表索引的方式没有什么不同。

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)

Unless you /need/ to use a list for an exercise, I'd argue that it's the incorrect data structure for this. 除非您需要使用列表进行练习,否则我会认为这是不正确的数据结构。

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})')

The above is just off the top of my head and untested, but demonstrates the idea. 以上只是我的脑海,未经测试,但演示了这个想法。 You could also store the values as an indexed list or something to that effect, I just like dicts for this simple case for readability and easy error handling. 您也可以将值存储为索引列表或具有这种效果的东西,我喜欢这种简单情况下的字典,以提高可读性和易于处理错误。

Solution

It is likely you will eventually want to extend your list of fruits. 您最终可能会想要扩展水果清单。 The following solution makes this simpler by encapsulating all the required information in a dict . 通过将所有必需的信息封装在dict ,以下解决方案使此操作更简单。

Code

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)

Output 输出量

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]]

Adding a fruit 加水果

A fruit can be dynamically added like so. 可以像这样动态添加水果。

for col, value in zip(lst, ['mango', 0.99, 5]):
    col.append(value)

update_fruits(lst, info)

print(lst)

Output 输出量

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]]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM