我有一个清单
301
我想按组合并列表中的值,以便获得:
a = [(1,2),(1,3),(4,5),(6,7),(8,7)]
顺序无关紧要,但是基于连接性的组很重要。尚未能找到解决方法,不胜感激!
答案 0 :(得分:2)
您可以使用集合交集来测试两个集合之间是否有任何共同的值,并且可以使用集合并集来合并两个集合:
o/p:
changed: [localhost] => {"backup_file": "user.27018.2018-12-04@21:29:58~", "changed": true, "msg": "2 replacements made"
cat <file_name? | grep clear_me
def **#clear_me**
**#clear_me**
b = []
for p in map(set, a):
for i, s in enumerate(b):
if s & p:
b[i] |= p
break
else:
b.append(p)
变为:
b
然后,您可以根据需要将其转换为所需的已排序元组列表:
[{1, 2, 3}, {4, 5}, {8, 6, 7}]
b = [tuple(sorted(s)) for s in b]
变为:
b
答案 1 :(得分:0)
一些for循环会完成这项工作:
a = [(1,2),(1,3),(4,5),(6,7),(8,7)]
unions = [[i1,i2] for i1,x in enumerate(a) for i2,y in enumerate(a) for z in x if z in y and i2!=i1]
for c in unions:
if c[::-1] in unions: unions.remove(c[::-1])
b = [e for i,e in enumerate(a) if i not in [y for x in unions for y in x]]
for c in unions:b.append(tuple(set(a[c[0]]+a[c[1]])))
print sorted(b)