I have a list of items and it outputs a list of list:
JavaScript
x
6
1
item_list = ['book', 'pen']
2
output = [
3
['pencil', 'eraser', 'pen', 'glue', 'folders'],
4
['notepad', 'book','pencil', 'markers','ruler','scissors']
5
]
6
Is there a way to get the output as a unique list of items that contains the top 3 items from each sublist but also not in the initial item_list
?
so that the output will look like (in the exact order):
JavaScript
1
2
1
new_output = ['pencil', 'eraser', 'glue', 'notepad', 'markers', 'ruler']
2
or if possible:
JavaScript
1
2
1
new_output = ['pencil', 'notepad', 'eraser', 'markers', 'glue','ruler']
2
Advertisement
Answer
You must keep a set
of already seen items to find the unique ones. A trivial implementation would be:
JavaScript
1
13
13
1
item_list = ['book', 'pen']
2
output = [['pencil', 'eraser', 'pen', 'glue', 'folders'],
3
['notepad', 'book', 'pencil', 'markers', 'ruler', 'scissors']]
4
5
already_seen = set(item_list)
6
new_output = []
7
for sublist in output:
8
new_sublist = [item for item in sublist if item not in already_seen]
9
new_output.extend(new_sublist[:3])
10
already_seen |= set(new_sublist[:3])
11
12
print(new_output)
13
output:
JavaScript
1
2
1
['pencil', 'eraser', 'glue', 'notepad', 'markers', 'ruler']
2