pythonarrayslistfor-loop

How to sum the selected elements from an array in python? (Multiple Inputs)


Here's the code:

PRICE = [1000, 1100, 1200, 1300, 1400, 1500]
x = raw_input() 

for i, v in enumerate(PRICE):

print total price

For example the user inputs "1 3 2 2" So the x is the multiple inputs I get from the user. How do I sum them up? With the answer should be 1100 + 1300 + 1200 + 1200 = 4800 I want to create a code that even if I change the inputs I will still be able to sum them up. Like if I change x to 2 2 2 1 it would sum for me to 4700.


Solution

  • You can turn the user input into indexes like this:

    print sum(PRICE[int(a)] for a in x.split())
    

    But it will only work if the raw_input has the format you said: integers split by whitespace and of course it's prone to IndexError: list index out of range if values greater than the list length are provided.

    EDIT: removed intermediary list creation as martineau suggested in the comments