I have a list named
l=[('Altamont','TN'),('Baxter','TN'),('Norway','SC'),('Trenton','SC')]
initially, which is in the order of ('cities', 'states')
After sorting based on states and cities, and writing to CSV
by below the functions,
def calcDistance(self):
filePath = self.dlg.fileNameEdit.text()
l=[('Altamont','TN'),('Baxter','TN'),('Norway','SC'),('Trenton','SC')]
sorted(l, key=operator.itemgetter(1,0))
self.writeToFile(l, filePath)
def writeToFile(self, l, filePath):
fileCSV = open(filePath, "w")
for i in l:
fileCSV.write(i)
fileCSV.write(",")
fileCSV.write("\n")
QMessageBox.information(self.dlg, "Number of Cities Near", str(len(lsOfCities)) + " citie(s) are written to "+filePath)
fileCSV.close()
self.dlg.close()
After it runs, I will be getting a CSV
file as below:
'Baxter','TN'
'Altamont','TN'
'Trenton','SC'
'Norway','SC'
I want to know that whether there is any possible way in Python2.7
, if I do sorting on the second column (i.e states) of the CSV
, the cells corresponding to that should also be sorted?
like
'Norway','SC'
'Trenton','SC'
'Altamont','TN'
'Baxter','TN'