【问题标题】:How to group elements in a list of lists in Python?如何在 Python 中对列表中的元素进行分组?
【发布时间】:2019-03-31 18:09:14
【问题描述】:

我正在尝试将顶点列表按其邻域大小有效地分组/嵌套到顶点列表列表中。

邻域大小是顶点v的一个属性,可以通过调用len(v.neighbours)获得。

我的输入是一个未排序的顶点列表。我试图获得的输出应该是这样的:

[[all vertices with len(v.neighbours) == 1], [... == 2], [... == 4]]    

它应该是一个列表列表,其中每个子列表包含具有相同邻域大小的顶点,从小到大排序,没有空列表。我不需要子列表的索引来映射到所包含顶点的邻域大小。

我知道如何通过列表理解来实现这一点,但效率相当低:

def _group(V: List[Vertex], max: int) -> List[List[Vertex]]:
    return [[v for v in V if v.label == i] for i in range(max)]

此外,我不想将最大邻域大小作为参数传递,而是在分组期间计算它,并且我也在寻找一种在分组期间过滤掉空列表的方法。

我已经研究了对顶点进行分组的更有效的方法,例如使用字典作为中间步骤,但我没有设法产生工作结果。

谁能告诉我对顶点列表进行分组/嵌套的最有效方法?

在此先感谢,如果之前已经发布过,很抱歉,但我在另一个问题中找不到我想要的内容。

【问题讨论】:

  • 您能否提供一个示例输入和输出作为MCVE

标签: python python-3.x


【解决方案1】:

遍历输入,将结果放入中间字典,将字典处理成您想要的输出。

temp_result = defaultdict(list)

for v in vertices:
    temp_result[neighborhood_size(v)].append(v)

max_size = max(temp_result.keys())

return_val = list()
for i in range(max_size):
    if temp_result[i]: # check if empty
        return_val.append(temp_result[i])

【讨论】:

    【解决方案2】:

    你可以这样构建它:

    from collections import defaultdict
    
    # Create a dict {nb_of_neighbours:[corresponding vertices]}
    vertices_by_neighbours = defaultdict(list)
    for v in vertices:
        vertices_by_neighbours[len(v.neighbours)].append(v)
    
    # Create the output list, sorted by number of neighbours    
    out = []
    for nb_neighbours in sorted(vertices_by_neighbours):
        out.append(vertices_by_neighbours[nb_neighbours])
    
    # Max number of neighbours, in case you want it...
    max_neighbours = max(vertices_by_neighbours)
    

    【讨论】:

      猜你喜欢
      • 2017-01-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多