简体   繁体   中英

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 .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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