简体   繁体   中英

How to read a graph from a file in python to get its adjacency list?

I am reading from a file which has numbers which represent a graph and its adjacency list.First number is the vertex and the remaining are the neighbors.

Suppose if i have a string of space separated numbers stored in string: 1 2 3 4.

How do i split it such that x=1 and y is a list [2,3,4]?

         y=[]
         g=open('graph','r')
         for line in g:
             x,y=line.split()

In Python 3 you could do:

x, *y = line.split()

but in Python 2 you need to split to one variable first, then assign to x and y :

values = line.split()
x, y = values[0], values[1:]

If these need to be integers instead of strings, you need to map the values to int() first:

x, *y = map(int, line.split())

or, Python 2 again:

values = map(int, line.split())
x, y = values[0], values[1:]

Python 3 demo:

>>> 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])

Here's a solution using Namedtuple [1] to store the data in an object oriented way.

Namedtuple is a generator to create small classes for storing data. The generated classes can print themselves, which is nice for debugging. However these objects are immutable, to change anything you must create new objects.

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)

You can get the first vertex number with:

graph[0].vert

And the first adjacency list with

graph[0].adj

[1] http://docs.python.org/2/library/collections.html#collections.namedtuple

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM