我试图找出如何删除列表列表中的重复项的方式,如果该元素已经存在于任何列表中,我希望不再添加它。
这是整个
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]]
谢谢
答案 0 :(得分:0)
我的答案是基于您对问题的文字描述。
尝试一下(代码注释中的说明):
.daily {
position: relative;
top: 70px;
height: 110px;
border: 1px solid black;
margin: 0 20px 0 20px;
}
输出:
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)
答案 1 :(得分:0)
有了Thaer的代码,我得到了,仍然不是预期的,但几乎是:
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]]