I have a list of lists
my_list = [["a", "b", "c"],
["d", "f", "g"],
["h", "b", "i"]]
I want to remove all elements in my_list where element[1] is not unique. So the result after performing this operation is either
my_list = [["d", "f", "g"]]
or a new list also works
new_list = [["d", "f", "g"]]
My current method is:
from collections import Counter
y_list = []
for element in my_list:
x, y, z = element
y_list.append(y)
count_dict = dict(Counter(y_list))
unique_y_list = []
for y, count in count_dict.items():
if count == 1:
unique_y_list.append(y)
valid_elements = []
for element in my_list:
x, y, z = element
if y in unique_y_list:
valid_elements.append(element)
This works but doesn't seem efficient. Help with a more pythonic way to achieve my desired result? Preserving order is not important.
unique_list, and checkif y in unique_y_list:, instead, useif count_dict[y] == 1: valid_elements.append(element)dict(Counter(y_list))is unecessary. aCounteris a dict already