1

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.

5
  • 1
    What do you mean by 'where element[1] is not unique.' ? Commented Sep 26, 2020 at 19:09
  • I mean any element where index[1] of that element occurs more than once in my_list. my_list [0] [1] == "b" ; my_list [2] [1] == "b" ; remove these elements Commented Sep 26, 2020 at 19:22
  • The only thing inefficint is how you re-construct the valid elements. Don't create a list, unique_list, and check if y in unique_y_list:, instead, use if count_dict[y] == 1: valid_elements.append(element) Commented Sep 26, 2020 at 19:28
  • also, dict(Counter(y_list)) is unecessary. a Counter is a dict already Commented Sep 26, 2020 at 19:28
  • @juanpa.arrivillaga thanks! Commented Sep 26, 2020 at 19:42

1 Answer 1

2

I'd create a Counter of elements in the index 1, and then use it to check if each list's element at index 1 is unique:

from collections import Counter
c = Counter(x[1] for x in my_list)
result = [l for l in my_list if c[l[1]] == 1]
Sign up to request clarification or add additional context in comments.

2 Comments

This is pretty much what the OP is doing.
@Mureinik thank you, exactly what I was looking for, fewer lines of code

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.