![](/img/trans.png)
[英]Read a file with an edge list for a graph and create adjacency list in Python
[英]How to read a graph from a file in python to get its adjacency list?
我正在從一個文件中讀取,該文件具有代表圖形及其鄰接列表的數字。第一個數字是頂點,其余的是鄰居。
假設我有一個用空格分隔的數字字符串存儲在字符串中:1 2 3 4。
我如何拆分它,使x = 1和y為列表[2,3,4]?
y=[]
g=open('graph','r')
for line in g:
x,y=line.split()
在Python 3中,您可以執行以下操作:
x, *y = line.split()
但是在Python 2中,您需要先拆分為一個變量,然后分配給x
和y
:
values = line.split()
x, y = values[0], values[1:]
如果這些需要是整數而不是字符串,則需要首先將值映射到int()
:
x, *y = map(int, line.split())
或者,再次使用Python 2:
values = map(int, line.split())
x, y = values[0], values[1:]
Python 3演示:
>>> x, *y = '1 2 3 4'.split()
>>> x, y
('1', ['2', '3', '4'])
>>> x, *y = map(int, '1 2 3 4'.split())
>>> x, y
(1, [2, 3, 4])
Python 2:
>>> values = '1 2 3 4'.split()
>>> x, y = values[0], values[1:]
>>> x, y
('1', ['2', '3', '4'])
>>> values = map(int, '1 2 3 4'.split())
>>> x, y = values[0], values[1:]
>>> x, y
(1, [2, 3, 4])
這是使用Namedtuple [1]以面向對象的方式存儲數據的解決方案。
Namedtuple是一個生成器,用於創建用於存儲數據的小類。 生成的類可以自行打印,這對於調試非常有用。 但是,這些對象是不可變的,要更改任何內容,必須創建新的對象。
from collections import namedtuple
VertexInfo = namedtuple("VertexInfo", "vert, adj")
graph = []
g = open('graph','r')
for line in g:
nums = line.split()
info = VertexInfo(vert=nums[0], adj=nums[1:])
graph.append(info)
您可以使用以下方法獲得第一個頂點編號:
graph[0].vert
和第一個鄰接列表
graph[0].adj
[1] http://docs.python.org/2/library/collections.html#collections.namedtuple
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.