Home > Software engineering >  how can i rank elements in a csv file from lowest to highest?
how can i rank elements in a csv file from lowest to highest?

Time:06-15

I have a csv file that has a district, party, votes, states, and year rows. I want to rank every district from texas from the lowest number of votes to the highest number of democratic votes only from the year 2018, how can I achieve this in the most beginner code? Would I have to use selection/ insertion sort?

CodePudding user response:

If you were to do this using Java (not sure how beginner friendly it is), you could do something like

String s = Files.readString(pathToYourFile);

and then split the string into an array of strings, delineated by the new line character "\n".

Then you can parse the String into an object, delineated by the character "," since it is csv. Now you can make a List, and do a Collections.sort(yourList).

Or, you could use a SQL database :)

CodePudding user response:

This is how i would personality to it:

with open('data.csv') as f:
    file_content = f.read()


data = [line.split(';') for line in file_content.splitlines()]
sorted_data = sorted(data, key=lambda x: int(x[1]), reverse=True)

print('\n'.join(';'.join(x) for x in sorted_data))

CodePudding user response:

I would use bubble sort, it is the simplest algorithm for sorting numbers.

def bubble_sort(your_list):
    has_swapped = True

    index_of_votes_value = 0 #assuming the list is 2D, each year, and then within the year, the votes, party, etc.

    num_of_iterations = 0

    while(has_swapped):
        has_swapped = False
        for i in range(len(your_list) - num_of_iterations - 1):
            if your_list[i][index_of_votes_value] > your_list[i 1][index_of_votes_value]:
                # Swap
                your_list[i][index_of_votes_value], your_list[i 1][index_of_votes_value] = your_list[i 1][index_of_votes_value], your_list[i][index_of_votes_value]
                has_swapped = True
        num_of_iterations  = 1

This algorithm iterates through your list, it checks if each index is larger than the one after it, and if it is, it swaps them. It keeps going through the list until the list is in order.

  • Related