如何在Python中列出列表中的元素?

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

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

邻域大小是顶点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)]

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

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

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

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

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

一次通过输入,将结果放在中间字典中,将字典处理成您想要的输出。

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])

0
投票

你可以用这种方式构建它:

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