根据常用值合并列表

问题描述 投票:2回答:2

我有一份清单

a = [(1,2),(1,3),(4,5),(6,7),(8,7)]

我想合并列表中的值,以便我可以得到:

b = [(1,2,3),(4,5),(6,7,8)]

订单无关紧要,但基于连接的小组很重要。一直无法找到办法,任何帮助表示赞赏!

python python-3.x list
2个回答
2
投票

您可以使用set intersection来测试两个集之间是否存在任何共同值,并且可以使用set union来合并这两个集:

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, 2, 3), (4, 5), (6, 7, 8)]

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)
© www.soinside.com 2019 - 2024. All rights reserved.