I want to create a nested list with one or more of the below lists of tuples, with the order of the list based on user's preference.
Fruits=[("Apples",2),("Oranges",3),("Pineapples",5)]
Clothes=[("Jeans",10),("Shirts",5),("Dresses",15)]
Pets=[("Dogs",3),("Cats",4),("Turtles",2)]
The order of the nested list will depend on the preference of the user.For instance, if the user prefer pets over clothes over fruits. The list will look like this:
[[("Jeans",10),("Shirts",5),("Dresses",15)],[("Jeans",10),("Shirts",5),
("Dresses",15)],[("Apples",2),("Oranges",3),("Pineapples",5)]]
The user also have the option of picking only one or two items. For instance, if the user only cares about pet and then clothing (doesn't care about fruits), his/her list will look like this.
[[("Dogs",3),("Cats",4),("Turtles",2)],[("Jeans",10),("Shirts",5),
("Dresses",15)]]
The user input is a list with the preferences in order. For example:
preference= ["Pets", "Fruits", "Clothing"] # preference list for users who care about pets over fruits over clothing.
or
preference= ["Fruits", "Clothing"] # preference list for users who care about fruits over clothing (no regard for pets)
This is how I've tried to tackle the problem. First I create an empty list with a corresponding number of nested list:
empty_list=[[] for x in range (len(preferences)]
This creates a place holder for the number of nested list I need. I then run a bunch of conditional statement to pop in one list at the time:
if preference[0]=="Fruits":
empty_list[0]=Fruits
if preference[1]=="Clothes":
empty_list[1]=Clothes
empty_list[2]=Pets
elif preference[1]=="Pets":
empty_list[1]=Pets
empty_list[2]=Clothes
if preference[0]=="Pets":
empty_list[0]=Pets
if preference[1]=="Clothes":
empty_list[1]=Clothes
empty_list[2]=Fruits
elif preference[1]=="Fruits":
empty_list[1]=Fruits
empty_list[2]=Clothes
if preference[0]=="Clothes":
empty_list[0]=Clothes
if preference[1]=="Pets":
empty_list[1]=Pets
empty_list[2]=Fruits
elif preference[1]=="Fruits":
empty_list[1]=Fruits
empty_list[2]=Pets
My solution is inefficient and also causes problem with list assignment out of range if there are only two preference as opposed to three. Is there a more Pythonic way of writing this?
Any tip or guidance is most appreciated.