Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # GBTownsSortedByIncreasingPopulation
- # Reads and sorts data in order of increasing population
- # Writes this data to a seperate file
- # Empty arrays for file
- place = [];
- Type = [];
- population = [];
- latitude = [];
- longitude = [];
- opened = 0
- try:
- readFile = open('GBplaces.csv','r');
- opened = 1
- except:
- print('Could not open file.');
- # Skips headings of file
- next(readFile);
- # Using this as a check to see if the correct file is opened
- # Also used to see if it has sorted in right order when written
- if opened:
- for line in readFile:
- splitUp = line.split(',');
- place.append(splitUp[0]);
- Type.append(splitUp[1]);
- population.append(int(splitUp[2]));
- latitude.append(splitUp[3]);
- longitude.append(splitUp[4]);
- print(splitUp[0] + ',' + splitUp[1] + ',' + splitUp[2] + ',' + splitUp[3] + ',' + splitUp[4]);
- Headings = readFile.readline();
- readFile.close();
- # Write a file which is sorted in population ascending order
- writeFile = open('GBplacesSorted.csv','w');
- # sort population in acsending numerical order
- sortpopulation = sorted(population);
- # sort each other array by zipping it with sorted population
- sortedplace = [place for (population,place) in sorted(zip(population,place), key=lambda pair: pair[0])];
- sortedType = [Type for (population, Type) in sorted(zip(population, Type), key=lambda pair: pair[0])];
- sortedlatitude = [latitude for (population,latitude) in sorted(zip(population, latitude), key=lambda pair: pair[0])];
- sortedlongitude = [longitude for (population, longitude) in sorted(zip(population, longitude), key=lambda pair: pair[0])];
- # write a file which lists towns and cities in order of population (plus other info)
- writeFile.write(Headings);
- for i in range(0,len(place)):
- writeFile.write(str(sortedplace[i]) + ',' + str(sortpopulation[i]) + ',' + str(sortedType[i]) + ',' + str(sortedlatitude[i]) + ',' + str(sortedlongitude[i]));
- writeFile.close();
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement