我有2个列表:
edges = [[0,1],[0,2],[0,3],[1,2],[1,3]]
weight = [10,8,7,3,7]
edges代表连接2个节点以及相应权重的边的列表。
对于给定的起始节点,如edges [i] [0],我想根据给定的权重选择最短的连接点,因此在这种情况下,结果将如下所示:
connect = [[0,3],[1,2]]
weight = [7,3]
因为在连接到0 3的所有节点中,最接近的是1,对于1,2是最接近的。
我无法提出问题,不胜感激!
答案 0 :(得分:0)
edges = [[0,1],[0,2],[0,3],[1,2],[1,3]]
weight = [10,8,7,3,7]
connect = []
wght = []
In [8]: for i in set(e[0] for e in edges):
...: temp = [(a, b) for a, b in zip(edges, weight) if a[0] == i]
...: temp = min(temp, key=lambda x: x[1])
...: connect += [temp[0]]
...: wght += [temp[1]]
In [9]: connect
Out[9]: [[0, 3], [1, 2]]
In [10]: wght
Out[10]: [7, 3]
以防万一:
In [20]: [min([(a, b) for a, b in zip(edges, weight) if a[0] == i], key=lambda x: x[1]) fo
...: r i in set([e[0] for e in edges])]
Out[20]: [([0, 3], 7), ([1, 2], 3)]
答案 1 :(得分:0)
使用Pandas的另一种解决方案:
df = pd.DataFrame(edges, columns=['start','end'])
df['weight'] = weight
df.loc[df.groupby('start')['weight'].idxmin()]
结果为:
start end weight
0 3 7
1 2 3