简体   繁体   English

如何从重复元素的列表列表中删除元素?

[英]How to remove elements from a list of lists where an element is repeated?

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.我想删除my_list中 element[1] 不唯一的所有元素。 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?以更pythonic的方式帮助实现我想要的结果? Preserving order is not important.保持秩序并不重要。

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:我会在索引 1 中创建一个元素Counter ,然后使用它来检查索引 1 处每个列表的元素是否唯一:

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]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM