簡體   English   中英

如何從重復元素的列表列表中刪除元素?

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

我有一份清單

my_list = [["a", "b", "c"],
           ["d", "f", "g"],
           ["h", "b", "i"]]

我想刪除my_list中 element[1] 不唯一的所有元素。 所以執行此操作后的結果是

my_list = [["d", "f", "g"]] 

或者一個新的列表也有效

new_list = [["d", "f", "g"]]

我目前的方法是:

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)

這有效,但似乎效率不高。 以更pythonic的方式幫助實現我想要的結果? 保持秩序並不重要。

我會在索引 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