gpt4 book ai didi

python - 列表顺序不符合预期

转载 作者:行者123 更新时间:2023-12-01 04:37:25 25 4
gpt4 key购买 nike

我有一个列表node_list

In [1]: node_list
Out[1]: ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 1, 2, 3, 4, 5, 6]

我将节点添加到 NetworkX来自 node_list

的图 G
In [2]: import networkx as nx

In [3]: G = nx.Graph()

In [4]: G.add_nodes_from(node_list)

但是当我获取节点列表时,模式发生了变化!

In [5]: list(G.nodes())
Out[5]: ['a', 1, 'c', 'b', 'e', 'd', 'g', 'f', 'i', 'h', 'j', 2, 3, 4, 6, 5]

我希望 Out[5]node_list 具有相同的模式,但这没有发生。怎么办?

最佳答案

From the docstring NetworkX.Graph:

Examples
--------
Create a graph object that tracks the order nodes are added.
>>> from collections import OrderedDict
>>> class OrderedNodeGraph(nx.Graph):
... node_dict_factory=OrderedDict
>>> G=OrderedNodeGraph()
>>> G.add_nodes_from( (2,1) )
>>> G.nodes()
[2, 1]
>>> G.add_edges_from( ((2,2), (2,1), (1,1)) )
>>> G.edges()
[(2, 1), (2, 2), (1, 1)]

关于python - 列表顺序不符合预期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31489566/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com