繁体   English   中英

在python列表列表中对相关项进行分组

[英]group correlate items in python list of lists

我有以下形式的清单:

list = [ [['item1'], ['property1','property2','property3']], [['item2'],['property1', 'property4']], ..., [['itemN'],['property5']]]

我要构建另一个列表列表,将上述所有项目与它们共享至少一个属性的项目组合在一起。 例如:

new_list = [['item1','item2'], .., ['itemN']]

请注意,即使项目间接共享属性,也应将它们分组在一起。 如果例如item1与item2具有公共属性,而item2与item3具有公共属性,而item1与item3不共享任何属性,则它们仍应归为一组。

我的尝试是在原始列表中添加一个布尔值(以便不需要时不再重复),并使用以下功能:

list = [ [['item1'], ['property1','property2','property3'], True], [['item2'],['property1', 'property4'], True], [['itemN'],['property5'], True]]

def group_correlates(list):
    result = []
    for i, entry in enumerate(list):
        correlates = []
        items = entry[0]
        properties = entry[1]
        if entry[2]: # if not already grouped (True)
            correlates.append(items)
        for j, other_entry in enumerate(list):
            flag = other_entry[2]
            if not i == j:
                if flag:
                    other_properties = other_entry[1]
                    other_items = other_entry[0]
                    for property in properties:
                        if property in other_properties:
                            other_entry[2] = False # do not visit again
                            correlates.append(other_items)
                            result.append(correlates)
    return result

但我明白了:

[[['item1'], ['item2']], [['item1']]]

即使我能做到这一点,我也肯定有一种更优雅的方法来完成同样的事情

为什么不使用dict然后使用itertools模块中的groupby

这是如何执行此操作的示例:

from itertools import groupby

data = [[['item1'], ['property1','property2','property3']], [['item2'],['property1', 'property4']], [['itemN'],['property5']]]

aa = {}
for k, v in data:
    for j in v:
        try:
            aa[j] += k
        except KeyError:
            aa[j] = k


new_list = [k for k,_ in groupby(sorted(aa.values()), lambda x: x)]
print(new_list)

或者,您可以使用collections模块中的defaultdict

from collections import defaultdict
from itertools import groupby

data = [[['item1'], ['property1','property2','property3']], [['item2'],['property1', 'property4']], [['itemN'],['property5']]]

bb = defaultdict(None)

for k, v in data:
    for j in v:
        bb[j] = k


new_list = [k for k,_ in groupby(sorted(bb.values()), lambda x: x)]
print(new_list) 

两者都将输出:

[['item1', 'item2'], ['item2'], ['itemN']]

首先将您的列表转换成如上所述的字典。

list1 = [ [['item1'], ['property1','property2','property3']], 
          [['item2'], ['property1', 'property4']],
          [['item3'], ['property5', 'property6']]
        ]

dict1 = {item[0][0]: item[1] for item in list1}

然后:

new_list = []

for key in dict1:
    target = dict1[key]
    for k, v in dict1.items():
        if k != key and len(set(target).intersection(set(v))) != 0:
            new_list.append([key, k])
    new_list = [sorted(i) for i in new_list] # sort sublists
    new_list = [list(t) for t in set(map(tuple, new_list))] # remove dupes

flat = [item for sublist in new_list for item in sublist] # flatten list
unique = list(set(dict1.keys()).difference(set(flat)))
new_list.append(unique) # add unique keys

new_list
Out[76]: [['item1', 'item2'], ['item3']]

“二分”主要是术语。 要点是要找到连接的子图。

将所有嵌套列表放入“打开”列表中……您需要处理此列表中的所有内容。 当它为空时,您就完成了。 开始一个新的子图列表-这是您提到的“列表列表”。

将项目列表和属性列表初始化为空列表。

选择一个项目并将其放入子图列表。 现在,在属性和项目之间切换,直到没有添加任何内容:

  1. 对于您刚刚添加的每个新项目(第一次只有该初始项目),(在属性列表中)添加该项目的所有属性。 保留哪些属性是新的属性列表。
  2. 从“打开”列表中删除这些项目(及其属性)。
  3. 对于刚添加的每个属性,(在项目列表中)添加具有该属性的每个项目。 保留刚刚添加的项目的列表。
  4. 重复步骤1-3,直到未添加任何新内容为止。

此时,项目列表和属性列表描述了一个封闭的子图。 将该对添加到主子图列表中。

返回,将项目和属性列表重置为空列表,然后从新的初始项目开始。 继续执行此操作,直到用尽所有项目。 “打开”列表现在为空; 现在,所有项目和属性都显示在子图列表中。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM