سؤال

I have a CSV file containing an n * n distance matrix, and here's a part of view,

enter image description here

I want to use python to edit this CSV, making elements in the diagonal of the matrix replaced by 1, how should I do?

I am using python 2.7.4 under Windows 8.1 x64.

هل كانت مفيدة؟

المحلول

probably best to create a new csv from the old one. (untested)

import csv

newlines = []
with open('csvfilename.csv', 'rb') as csvfile:
  reader = csv.reader(csvfile)
  i=0
  for row in reader:
    newlines.append(row[:i] + [1] + row[i+1:])
    i+=1
with open('newcsvfilename.csv','wb') as csvfile:
  writer = csv.writer(csvfile)
  writer.writerows(newlines)
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top