簡體   English   中英

從二維列表中刪除重復的元素(不是列表),Python

[英]Remove duplicated elements (not lists) from 2D list, Python

我想從出現不止一次的列表列表中刪除所有元素,並且正在尋找比這更平滑的解決方案: 從 Prolog 中的列表列表中刪除重復元素

我不會像這里那樣嘗試刪除父列表中的重復列表: How to remove duplicates from nested lists

考慮這個 Int:

list = [
[1, 3, 4, 5, 77],
[1, 5, 10, 3, 4],
[1, 5, 100, 3, 4], 
[1, 3, 4, 5, 89], 
[1, 3, 5, 47, 48]]

所需的 output:

new_list= [
[77],
[10],
[100], 
[89], 
[47, 48]]

謝謝。 我將在 Pandas 中使用它:new_list 將作為一個新列,與原始列相比,每行具有唯一值。

可能有更流暢的方法,但這有效:

from collections import Counter

mylist = [
[1, 3, 4, 5, 77],
[1, 5, 10, 3, 4],
[1, 5, 100, 3, 4], 
[1, 3, 4, 5, 89], 
[1, 3, 5, 47, 48]]


flat = [y for x in mylist for y in x]    
count = Counter(flat)
uniq = [x for x,y in count.items() if y == 1]
new_list = [[x for x in y if x in  uniq] for y in mylist]

這使

[[77], [10], [100], [89], [47, 48]]
for bi,lst in enumerate(l):
    for el in lst:
        for i in range(len(l)):
            if bi != i:
                if el in l[i]:
                    print(f'element:{el}')
                    print(f'passing over list:{l[i]}')
                    l[i].remove(el)
                    try: l[bi].remove(el)
                    except: continue

那個不是很有用,但我看到通常其他答案(包括您的鏈接帖子)使用另一個模塊,所以我嘗試了不同的方法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM