我正在尝试在python中对嵌套列表进行分类,我的列表很大,由于项目索引错误,我还没有成功。我的目标是,如果列表中的两个项目具有相同的成员,则用item2扩展item1并删除item2。我在python上没有足够的经验。希望你能帮忙
My pseudo code
L = [[0, 1], [2, 3], [4, 5, 13], [6, 7], [2, 8],[3, 10, 11], [12, 13]]
for i in range(len(L)-1):
for j in range(i+1,len(L)):
if i!=j and set(L[i]) & set(L[j]) != set():
L[i].extend(L[j])
L.remove(L[j])
expected L = [[0,1], [6, 7], [2, 3, 2, 8, 3, 10, 11], [4, 5, 13, 12, 13]]
答案 0 :(得分:2)
L = [[0, 1], [2, 3], [4, 5, 13], [6, 7], [2, 8],[3, 10, 11], [12, 13]]
out = []
while L:
current = L.pop(0)
out.append(current)
tmp = []
for v in L:
if set(v).intersection(current):
current.extend(v)
else:
tmp.append(v)
L = tmp
print(out)
打印:
[[0, 1], [2, 3, 2, 8, 3, 10, 11], [4, 5, 13, 12, 13], [6, 7]]
编辑:版本2:
L = [[0, 1], [2, 3], [4, 5], [6, 7], [8, 9],[10, 11], [1,3,5,7,9,11]]
out = []
while L:
current = L[0]
while True:
tmp = []
for i, v in enumerate(L[1:], 1):
if set(v).intersection(current):
current.extend(L.pop(i))
break
else:
tmp.append(v)
else:
break
out.append(current)
L = tmp
print(out)
打印:
[[0, 1, 1, 3, 5, 7, 9, 11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]]
对于L = [[0, 1], [2, 3], [4, 5, 13], [6, 7], [2, 8],[3, 10, 11], [12, 13]]
打印:
[[0, 1], [2, 3, 2, 8, 3, 10, 11], [4, 5, 13, 12, 13], [6, 7]]