2 回答
TA贡献1712条经验 获得超3个赞
您需要使用递归:
def group(d, _start, _c = [], _seen = [], _used=[]):
r = [i for i in d if any(c in _start for c in i) and i not in _seen and i not in _used]
if not r:
yield set(_c)
for i in d:
if i != _start and i not in _used:
yield from group(d, i, _c=[], _seen=[], _used=_used+[i, *r])
else:
yield from group(d, _start, _c=_c+[i for b in r for i in b], _seen=_seen+r, _used=_used+r)
data = [[1, 7, 3], [1, 7, 5], [2, 0, 4], [2, 0, 6], [3, 7, 1], [3, 7, 5], [4, 0, 2], [4, 0, 6], [5, 7, 1], [5, 7, 3], [6, 0, 2], [6, 0, 4]]
result = list(map(list, {tuple(i) for i in group(data, data[0], _seen=[data[0]]) if i}))
输出:
[[0, 2, 4, 6], [1, 3, 5, 7]]
TA贡献1829条经验 获得超7个赞
这个问题可以使用递归解决,特别是尾递归:
def merge(lists, results=None):
if results is None:
results = []
if not lists:
return results
first = lists[0]
merged = []
output = []
for li in lists[1:]:
for i in first:
if i in li:
merged = merged + li
break
else:
output.append(li)
merged = merged + first
results.append(list(set(merged)))
return merge(output, results)
结果如下所示:
>>> lists = [[1, 7, 3], [1, 7, 5], [2, 0, 4], [2, 0, 6], [3, 7, 1], [3, 7, 5], [4, 0, 2], [4, 0, 6], [5, 7, 1], [5, 7, 3], [6, 0, 2], [6, 0, 4]]
>>> merge(lists)
[[1, 3, 5, 7], [0, 2, 4, 6]]
添加回答
举报
