将CSV转换为邻接列表

时间:2019-08-01 22:09:04

标签: python csv data-structures adjacency-list

仅当存在距离时将CSV文件转换为邻接列表,如果城市之间的距离为-1则不要添加

def readFile(filename):


    with open(filename) as csvfile:
        csv_reader = csv.reader(csvfile, delimiter=',')
        line_count = 0
        cities=[]
        distance=[]
        for row in csv_reader:
            if line_count == 0:
                cities+=row[1:]
                line_count += 1
            else:
                for column in row:
                    line_count += 1
        return cities

filename='cities.csv'

readFile(filename)

CSV文件city.csv

city,El Paso,San Antonio,Houston,Amarillo

El Paso,-1,809,1080,-1

San Antonio,809,-1,306,716

Houston,1080,306,-1,857

Amarillo,-1,716,857,-1

1 个答案:

答案 0 :(得分:0)

使用图结构可能是这样的:

class Node(object):
    def __init__(self, key=None, value=None):
        self.key = key
        self.value = value
        # List of adjacent node objects
        self.adj = []

class Graph(object):
    def __init__(self):
        # Adjacency list
        self.nodes = {}

    def add(self, f, t):
        if f not in nodes:
            self.nodes[f] = Node(key=f)
        if t not in nodes:
            self.nodes[t] = Node(key=t)
        if t not in self.nodes[f].adj:
            self.nodes[f].adj.append(self.nodes[t])

# Create graph object
graph = Graph()
# Loop the elements in the row
# ...
for c in range(len(row)):
    if c == 0:
        city = row[c]
    else:
        if row[c] == -1:
            graph.add(city,cities[c])
# ...