将Python列表转换为NetworkX图的实现方案求助
Solution to Convert List of Lists to NetworkX Edges
Let's walk through how to turn your nested list into the exact NetworkX edges you need. The key idea is to extract unique node-weight-node pairs from each sublist and avoid adding duplicate edges to the graph.
Approach
- Iterate through each sublist: Each entry is a chain of nodes connected by weights, so we'll process them in groups of three (node → weight → node).
- Track unique edges: Since multiple sublists share the same edges, we'll use a set to keep track of edges we've already added (to avoid duplicates in the undirected graph).
- Add edges to the graph: For each unique node-weight-node triplet, add the edge to the NetworkX graph with its corresponding weight.
Complete Code
import networkx as nx # Your input data input_list = [ ['Мама мыть', 10, 'рама'], ['Мама мыть', 10, 'рама', 5, 'долго'], ['Мама мыть', 10, 'рама', 3, 'вчера'], ['Мама мыть', 10, 'рама', 3, 'вчера', 1, 'поздно'] ] # Initialize graph and edge tracker G = nx.Graph() added_edges = set() for sublist in input_list: # Step through the sublist in pairs of node-weight-node for i in range(0, len(sublist) - 1, 2): source = sublist[i] weight = sublist[i + 1] target = sublist[i + 2] # Use a sorted tuple to represent undirected edges (avoids duplicate (a,b) and (b,a)) edge_key = tuple(sorted((source, target))) if edge_key not in added_edges: G.add_edge(source, target, weight=weight) added_edges.add(edge_key) # Verify the result (optional) for u, v, data in G.edges(data=True): print(f"G.add_edge('{u}', '{v}', weight={data['weight']})")
Explanation
- Edge tracking: The
added_edgesset uses sorted tuples to ensure we don't add the same undirected edge twice (since('рама', 'вчера')is identical to('вчера', 'рама')in an undirected graph). - Loop logic: The
range(0, len(sublist)-1, 2)loop steps through each sublist in increments of 2, so we always grab a node, its connecting weight, and the next node in the chain.
When you run this code, it will output exactly the edges you're targeting:
G.add_edge('Мама мыть', 'рама', weight=10) G.add_edge('рама', 'долго', weight=5) G.add_edge('рама', 'вчера', weight=3) G.add_edge('вчера', 'поздно', weight=1)
内容的提问来源于stack exchange,提问作者Alex Nikitin
相关产品推荐
相关产品推荐

