If the only rule is that each entry in the list can be a string representing a single item (without commas) or a list of items separated by commas, you can just use str.split(',')
on each entry.
Notice the terminology there, it's important:
- The list is what you have and it contains a number of string entries;
- Each string entry is either an item or a comma-separated list of items;
- Each item is a thing you want as a separate entry in the new list.
For an entry without commas, str.split
will give you a list with just that one item:
>>> 'cherry'.split(',')
['cherry']
For an item with commas, it will give you a list containing all the items in the entry:
>>> 'cherry,banana'.split(',')
['cherry', 'banana']
So you just need to process the list and, for each entry in the list, split it into an item list and use each of those items to construct a new list:
[item for entry in my_list for item in entry.split(',')]
| | \ / \ /
| | \ get each entry / \ get each item of entry /
| | \______________/ \______________________/
| |
+--+------> deliver all items into new list
You can see this working in the following transcript:
>>> my_list = ['orange', 'cherry,strawberry', 'apple', 'blueberry,banana']
>>> [item for entry in my_list for item in entry.split(',')]
['orange', 'cherry', 'strawberry', 'apple', 'blueberry', 'banana']
Just keep in mind that, if you want to handle entries with spaces like 'cherry, pie'
. you should probably remove extraneous spaces:
[item.strip() for entry in ...