比较列表列表并创建集群

社会演员多 python 263

原文标题compare list of lists and create clusters

我有一个列表,其中包含 10,000 个不同长度的字符串列表。对于这个问题,我会说得简单一些,并举一个只有一个列表的例子,它有 10 个列表,如下所示。

list = [['a','w','r', 't'], ['e','r', 't', 't', 'r', 'd', 's'], ['a','w','r', 't'], ['n', 'g', 'd', 'e', 's'], ['a', 'b', 'c'], ['t', 'f', 'h', 'd', 'p'], ['a', 'b', 'c'], ['a','w','r', 't'], ['s','c','d'], ['e','r', 't', 't', 'r', 'd', 's']]

我想要的是将每个列表与所有其他列表进行比较,并将相似的列表分组到一个新列表(称为集群)中,并将列表索引分组。

预期输出:

cluster_1_lists = [['a','w','r', 't'], ['a','w','r', 't'], ['a','w','r', 't']]

cluster_1_indices = [0,2,7]

cluster_2_lists = [['e','r', 't', 't', 'r', 'd', 's'],['e','r', 't', 't', 'r', 'd', 's']]

cluster_2_indices = [1,9]

cluster_3_lists = [['n', 'g', 'd', 'e', 's']]

cluster_3_indices = [3]

cluster_4_lists = [['a', 'b', 'c'], ['a', 'b', 'c']]

cluster_4_indices = [4,6]

cluster_5_lists = [['t', 'f', 'h', 'd', 'p']]

cluster_5_indices = [5]

cluster_6_lists = [['s','c','d']]

cluster_6_indices = [8]

你能帮我在python中实现这个吗?

原文链接:https://stackoverflow.com//questions/71476297/compare-list-of-lists-and-create-clusters

回复

我来回复
  • The Myth的头像
    The Myth 评论

    好的,所以在这里,我将基本上使用字典来制作集群。这是我所做的:

    list= [['a','w','r', 't'], ['e','r', 't', 't', 'r', 'd', 's'], ['a','w','r', 't'], ['n', 'g', 'd', 'e', 's'], ['a', 'b', 'c'], ['t', 'f', 'h', 'd', 'p'], ['a', 'b', 'c'], ['a','w','r', 't'], ['s','c','d'], ['e','r', 't', 't', 'r', 'd', 's']]
    cluster = {}
    
    for i in list:
        cluster[''.join(i)] = []
        cluster[''.join(i)+'_indices'] = []
    for j in range(len(list)-1):
        for k in cluster:
            if ''.join(list[j]) == k:
                cluster[k].append(list[j])
                cluster[k+'_indices'].append(j)
    print(cluster)
    

    第一个 for 循环基本上使用列表的联合名称创建一个键,因为您不能将键作为列表。然后,它将 val 存储为一个空列表,该列表将进一步附加。在第二个 for 循环中,它再次遍历列表,在其中我遍历了集群中的键(dict)。然后,它基本上检查联合列表是否等于键名,如果是,则附加值。输出将如下所示:

    Output: {'awrt': [['a', 'w', 'r', 't'], ['a', 'w', 'r', 't'], ['a', 'w', 'r', 't']], 'awrt_indices': [0, 2, 7], 'erttrds': [['e', 'r', 't', 't', 'r', 'd', 's']], 'erttrds_indices': [1], 'ngdes': [['n', 'g', 'd', 'e', 's']], 'ngdes_indices': [3], 'abc': [['a', 'b', 'c'], ['a', 'b', 'c']], 'abc_indices': [4, 6], 'tfhdp': [['t', 'f', 'h', 'd', 'p']], 'tfhdp_indices': [5], 'scd': [['s', 'c', 'd']], 'scd_indices': [8]}
    

    注意:根据需要创建单独的变量只会使代码混乱,python 有一个解决方案是字典,因此我使用了它。

    2年前 0条评论