【问题标题】:reduce lists given single value of 2d lists给定二维列表的单个值减少列表
【发布时间】:2018-10-29 14:30:05
【问题描述】:

我有 2 个列表:

edges = [[0,1],[0,2],[0,3],[1,2],[1,3]]
weight = [10,8,7,3,7]

edges 表示将 2 个节点连接在一起的边列表以及相应的权重。

对于给定的起始节点,如边缘[i][0],我想选择给定权重的最短连接点,因此在这种情况下,结果如下所示:

connect = [[0,3],[1,2]]
weight = [7,3]

因为在连接到 0 的所有节点中,3 是最近的一个,而对于 1,2 是最近的一个。

我无法提出问题,感谢任何帮助!

【问题讨论】:

标签: python python-3.x list graph-theory


【解决方案1】:
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)]

【讨论】:

    【解决方案2】:

    使用 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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-10-01
      • 2021-10-25
      • 1970-01-01
      • 1970-01-01
      • 2021-11-09
      • 1970-01-01
      • 1970-01-01
      • 2019-04-02
      相关资源
      最近更新 更多