How to create a list in Python, based of another master list and user input as index? -


i'm relatively new python.

i have list like

master = ['apple','banana','clementines','dates','fig','guava'] 

i user input like

choose fruits: > 1,3:5 

based on user input, want create sub-list like

selectedfruits = ['apple','clementines','dates','fig'] 

if perform command follows, error index string.

userinput = input() selectedfruits = master[userinput] 

can kindly help?

you can this;

master = ['apple','banana','clementines','dates','fig','guava'] inp = input().split(",") # input "1,3:5" selectedfruits = [] elem in inp:     if ":" in elem:         i, j = elem.split(":")         selectedfruits.extend(master[int(i):int(j)])     else:         = int(elem)         selectedfruits.append(master[i]) # ['banana', 'dates', 'fig'] 

assuming input entered 1 time commas, can split them first, put in loop.

what did in solution check ":" s in each input see if index. stack them in tuple such (i,j) later use indexes because tuple cannot used directly index.

and take care every time use these values have convert them integers because default inputs strings.

selectedfruits.extend(master[int(i):int(j)]) 

i used extend(), instead of append() in part because indexes use, causes return list inside list if hadn't done that:

['banana', ['dates', 'fig']] 

Comments

Popular posts from this blog

sql - VB.NET Operand type clash: date is incompatible with int error -

SVG stroke-linecap doesn't work for circles in Firefox? -

python - TypeError: Scalar value for argument 'color' is not numeric in openCV -