删除列表列表中的重复元素

2024-10-02 02:34:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图弄清楚如何删除列表列表中的重复项,如果元素已经存在于任何列表中,我希望不再添加它

这是全部

def listeAmis(n) : 
    liste = []
    print("Rentrez un numéro d'un ami de ",n)
    a = 0
    while a!="na": 
        a=input("tapez 'na' s'il n'y a pas d'autres amis")
        liste.append(a) 
    last = int(len(liste)-1)
    del liste[last]
    return liste



def initReseau(n) : 
    i = 0
    listeR = []
    while i<n : 
        listeR.append(listeAmis(i))
        i = i+1
    return listeR

def ami(r,i,j) : 
    if j in r[i] and i in r[j]: 
        return True
    else : 
        return False

def groupeAmis(r,i) : 
    groupe = [i]
    a = 0
    while a < n-1 :  
        res = all(ami(r,elem,a) for elem in groupe)
        if res :
            groupe.append(a)
        a=a+1
    return groupe


def groupeAmisPartition(r) : 
    liste=[]
    for i in range(0,n) : 
        T = groupeAmis(r,i)
        liste.append(T)
    return liste




n = 8
r = [[2, 3], [3, 5], [0, 3, 6, 7], [0, 1, 2, 4, 5, 6], [3, 7],[1, 3, 6, 7], [2, 3, 5], [2, 4, 5]]
groupeAmisPartition(r)

以下是我得到的:

[[0, 2, 3],[1, 3, 5],[2, 0, 3],[3, 0, 2],[4, 3],[5, 1, 3],[6, 2, 3],[7, 2]]

以下是我想要的:

[[0,2,3],[1,5],[4,7],[6]]

谢谢


Tags: in列表returnifdefunlastna
2条回答

我的答案是基于你对问题的文字描述

尝试以下操作(代码注释中的解释):

r = [[2, 3], [3, 5], [0, 3, 6, 7], [0, 1, 2, 4, 5, 6], [3, 7],[1, 3, 6, 7], [2, 3, 5], [2, 4, 5]]
done= []
big_new_lst = []
# for items in initial list
for i in r:
    # initialize empty "small list"
    new_lst = []
    # for item in list in initial list
    for c in i:
        # if item is not in our done list
        if c not in done:
            #add it to our done list
            done.append(c)
            # add it to our new small list
            new_lst.append(c)
    # add the small list to the big list if it's not empty
    if new_lst:
        big_new_lst.append(new_lst)

print (big_new_lst)

输出:

[[2, 3], [5], [0, 6, 7], [1, 4]]

用塔尔的代码,我得到了这个,仍然不是预期的,但几乎:

def groupeAmisPartition(r) : 
    liste=[]
    for i in range(0,n) : 
        T = groupeAmis(r,i)
        liste.append(T)
    done= []
    big_new_lst = []
    for i in liste:
        new_lst = []
        for c in i:
            if c not in done:
                done.append(c)
                new_lst.append(c)
        if new_lst:
            big_new_lst.append(new_lst)
    return big_new_lst

输出:

[[0, 2, 3], [1, 5], [4], [6], [7]]

相关问题 更多 >

    热门问题