Expand a comma separated item in a list

Advertisements

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.

>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]

Leave a ReplyCancel reply