简体   繁体   English

如何从python文件中读取图以获取其邻接表?

[英]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. 假设我有一个用空格分隔的数字字符串存储在字符串中:1 2 3 4。

How do i split it such that x=1 and y is a list [2,3,4]? 我如何拆分它,使x = 1和y为列表[2,3,4]?

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

In Python 3 you could do: 在Python 3中,您可以执行以下操作:

x, *y = line.split()

but in Python 2 you need to split to one variable first, then assign to x and y : 但是在Python 2中,您需要先拆分为一个变量,然后分配给xy

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: 如果这些需要是整数而不是字符串,则需要首先将值映射到int()

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

or, Python 2 again: 或者,再次使用Python 2:

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

Python 3 demo: 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: 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 [1]以面向对象的方式存储数据的解决方案。

Namedtuple is a generator to create small classes for storing data. Namedtuple是一个生成器,用于创建用于存储数据的小类。 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 [1] http://docs.python.org/2/library/collections.html#collections.namedtuple

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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