It was necessary to write a program that generates a graph with a random connection and present it as adjacency lists and save these lists in CSV format.
I made the output of the lists via print (), please tell us how to output the results to a CSV file so that in each separate line there is an adjacency list for a particular vertex.

import random n = 5 matrix = [[random.randint(0, 1) for i in range(n)] for j in range(n)] for i in range(n): matrix[i][i] = 0 for i in range(n): for j in range(n): matrix[j][i] = matrix[i][j] print(matrix) for i in range(n): print('Вершина', i+1, 'имеет связь с вершинами: ', end='') for j in range(n): if j == n-1 and matrix[i][j] != 0: print(j+1) continue elif j == n-1 and matrix[i][j] == 0: print() if matrix[i][j] != 0: print(j+1, end=' ') 

As a result of the program for the 5x5 matrix, the program displays the following data:
Vertex 1 is connected to vertices: 2 3 4 5
Vertex 2 is connected to vertices: 1 3 4
Vertex 3 is connected with vertices: 1 2
Vertex 4 is connected to vertices: 1 2 5
Vertex 5 is connected with vertices: 1 4

    1 answer 1

    Try:

     import random n = 5 matrix = [[random.randint(0, 1) for i in range(n)] for j in range(n)] for i in range(n): matrix[i][i] = 0 for i in range(n): for j in range(n): matrix[j][i] = matrix[i][j] print(matrix) with open('output.csv', 'w') as g: for i in range(n): print('{},'.format(i+1), end='', file=g) for j in range(n): if j == n-1 and matrix[i][j] != 0: print('{},'.format(j+1), file=g) continue elif j == n-1 and matrix[i][j] == 0: print("", file=g) if matrix[i][j] != 0: print('{},'.format(j+1), end='', file=g)