If I have two set of lists and I want them to be sorted into their categories. eg. if i have two list like below
x = ["fruits", "vegetables", "fruits", "meat"]
y = ["apples", "cabbage", "banana", "beef"]
and I want them to output like this
> fruits
apples
banana
vegetables
cabbage
meat
beef
how do i do it?
CodePudding user response:
I'd create a defaultdict
with an empty list
as the default item, and then iterate over the two lists (e.g., using zip
) and append each item of y
to the appropriate x
:
result = defaultdict(list)
for z in zip(x,y):
result[z[0]].append(z[1])
CodePudding user response:
You can do this with groupby:
import itertools
# Group
for categroy, items in itertools.groupby(
# groupby requires it to be sorted
sorted(
# combine the adjacent elements of both loops
zip(x,y)),
# group by the first element
key=lambda i:i[0]):
# print the category
print(category)
for item in items:
# print the item
print(f"\t{item[1]}")