Reputation: 13
I want to place the duplicates from one list in another list. In the follow example, I am attempting to create a list red_dup
that contains every item that contains a 'red' id that is duplicated. Similarly, I want to do the same for each food in a food_dup
list.
What I have:
values = [[1, 'red1', 'food4'], [1, 'red2', 'food4'], [1, 'red1', 'food9']]
The result I'm looking for:
red_dup = [[1, 'red1', 'food4'], [1, 'red1', 'food9']]
food_dup = [[1, 'red1', 'food4'], [1, 'red2', 'food4']]
In my code the "values" comes from a generator function from a class.
The function returns these values.
The 1 is the distance, and the red or blue is the entity distance from the food.
This is what code returns. The red underline is a X, Y coordinates.
Upvotes: 0
Views: 163
Reputation: 10624
Here is my suggestion:
values = [[1, 'red1', 'food4'], [1, 'red2', 'food4'], [1, 'red1', 'food9']]
red_dup = []
food_dup = []
for i in values:
red=[k for k in values if k[1]==i[1]]
if len(red)>1:
red_dup.extend(red)
food = [k for k in values if k[2]==i[2]]
if len(food)>1:
food_dup.extend(food)
red_dup=sorted(red_dup, key=lambda x: [x[1], x[2]])[::2]
food_dup=sorted(food_dup, key=lambda x: [x[2], x[1]])[::2]
>>>print(red_dup)
#[[1, 'red1', 'food4'], [1, 'red1', 'food9']]
>>>print(food_dup)
#[[1, 'red1', 'food4'], [1, 'red2', 'food4']]
Upvotes: 0
Reputation: 6121
you can use dict to store and filter for dupe values
from collections import defaultdict
res = defaultdict(list)
for item in values:
_, color, food = item
res[color].append(item)
res[food].append(item)
[v for v in res.values() if len(v) > 1]
result:
[[[1, 'red1', 'food4'], [1, 'red1', 'food9']],
[[1, 'red1', 'food4'], [1, 'red2', 'food4']]]
Upvotes: 1