Hi,
my first topic here.
I have a list like:
a = [['fruit','banana','apple'],['insect','ant','bee',wasp']]
I want to add an item to the list based on its category. For example, if the new item is 'butterfly'
, I want to add it to the list after checking that the 'insect'
sublist exists, so that a
becomes:
a = [['fruit','banana','apple'],['insect','ant','bee',wasp','butterfly']]
However, if the category is 'car'
and the item is 'ferrari'
, I want to create a new sublist called 'cars'
, and a 2nd subitem 'ferrari'
, so that a
becomes:
a = [['fruit','banana','apple'],['insect','ant','bee',wasp'],['car','ferrari']]
In other words, the category is the first item of each sublist, and is followed by all the items of that category.
Once I completed building the list, I would like to print it like this:
fruit: banana, apple
insect: ant, bee, wasp, butterfly
car: ferrari
What sort of code I need to do that quickly?
And BTW, is a list the best way to deal with this kind of problem? Maybe better to use another way to store those values?
Many thanks for your help.