python列表元素按条件分组_将Python列表列表根据重叠项分组

我有一个列表列表,我试图根据它们的项目对它们进行分组或聚类。如果上一个组中没有元素,则嵌套列表将开始一个新组。

输入:

paths = [

['D', 'B', 'A', 'H'],

['D', 'B', 'A', 'C'],

['H', 'A', 'C'],

['E', 'G', 'I'],

['F', 'G', 'I']]

我失败的代码:

paths = [

['D', 'B', 'A', 'H'],

['D', 'B', 'A', 'C'],

['H', 'A', 'C'],

['E', 'G', 'I'],

['F', 'G', 'I']

]

groups = []

paths_clone = paths

for path in paths:

for node in path:

for path_clone in paths_clone:

if node in path_clone:

if not path == path_clone:

groups.append([path, path_clone])

else:

groups.append(path)

print groups

预期产量:

[

[

['D', 'B', 'A', 'H'],

['D', 'B', 'A', 'C'],

['H', 'A', 'C']

],

[

['E', 'G', 'I'],

['F', 'G', 'I']

]

]

另一个例子:

paths = [['shifter', 'barrel', 'barrel shifter'],

['ARM', 'barrel', 'barrel shifter'],

['IP power', 'IP', 'power'],

['ARM', 'barrel', 'shifter']]

预期的输出组:

output = [

[['shifter', 'barrel', 'barrel shifter'],

['ARM', 'barrel', 'barrel shifter'],

['ARM', 'barrel', 'shifter']],

[['IP power', 'IP', 'power']],

]

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值