Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Expand a comma separated item in a list

I have two python lists of the following form:

grocery_list = ["apple", "whole milk, skim milk, 2% milk", "american cheese, cheddar cheese"]
grocery_cost = [10.5, 4.50, 2.40]

and I would like to convert them to a more easily read from list of the form:

grocery_list = ["apple", "whole milk" , "skim milk", "2% milk", "american cheese", "cheddar cheese"]
grocery_cost = [10.5, 4.50, 4.50, 4.50, 2.40, 2.40]

Essentially I have a series of lists where certain indexes are themselves comma separated lists.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

One possible solution is to iterate through the original grocery and pice together, split grocery by comma (assuming that comma is always the separator), and repeat the price the same number of times as the length of the grocery list after the split.

The sample code is shown below.

grocery_list = ["apple", "whole milk, skim milk, 2% milk", "american cheese, cheddar cheese"]
grocery_cost = [10.5, 4.50, 2.40]

updated_grocery_list = []
updated_grocery_cost = []
for g, c in zip(grocery_list, grocery_cost):
    g_list = [gg.strip() for gg in g.split(",")]  # split on comma and remove spaces
    updated_grocery_list.extend(g_list)
    updated_grocery_cost.extend([c] * len(g_list))

print(updated_grocery_list)
print(updated_grocery_cost)

# Output
# ['apple', 'whole milk', 'skim milk', '2% milk', 'american cheese', 'cheddar cheese']
# [10.5, 4.5, 4.5, 4.5, 2.4, 2.4]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading