So I've got a .txt
file as follows:
131,263.07
47,170.14
170,190.01
180,412.69
53,401.53
And I had to read the file so as to output the list like:
131 kms, $263.07
47 kms, $170.14
170 kms, $190.01
180 kms, $412.69
53 kms, $401.53
The code I used was:
def PrintList(table):
for line in table:
print(str(line[0]) + " kms, $" + str(line[1]))
file = open(input("Enter file name: "))
table = []
for line in file:
line = line.rstrip().split(",")
line[0] = int(line[0])
line[1] = float(line[1])
table.append(line)
PrintList(table)
file.close()
And now I'd like to sort the list in increasing order of price to obtain:
47 kms, $170.14
170 kms, $190.01
131 kms, $263.07
53 kms, $401.53
180 kms, $412.69
How would I implement this in Python? I've tried doing this using Selection Sort
but it just doesn't seem to be working.
Update: Thanks for the input so far. However, I have tried the sort function but I'd like to figure out how to implement this using Selection Sort
.
Update: I am unable to post the Selection Sort
code that I have used as I have overwritten it, nonetheless given below is an example of the code (which I have used to sort a random list of distances) which I had to modify to sort the aforementioned list in increasing order of price. Hope it's sufficient.
def selectionSort(distance):
n = len(distance)
for i in range(n):
minPlace = searchMin(distance)
swap(distance, i, minPlace+i)
def searchMin(distance):
minPlace = 0
n = len(distance)
for i in range(1, n):
if distance[i] < distance[minPlace]:
minPlace = i
return minPlace
def swap(distance, i, j):
temp = distance[i]
distance[i] = distance[j]
distance[j] = temp
If there's an easier way to implement this, please let me know. Thanks in advance. Cheers.
Is it absolutely necessary to implement selection sort? I would go with
sorted
:where
instructs
sorted
to use the value of the element with index1
(price) to compare your objects.after your for-loop:
Sorted_table now contains your tabular data, sorted by the 2nd column. You can then pass
sorted_table
to your PrintList function. An alternative that avoids the lambda:For more on python sorting, see: https://wiki.python.org/moin/HowTo/Sorting
Python lists come with a
sort
method already. You can simply call it, specifying akey
argument to determine how to sort.Note that I made a couple of additional changes to your program, namely renaming PrintList in accordance with PEP8, and using the
with
statement so that the file gets closed automatically.If insist on using Selection Sort (it will be worse than Python's default sorting), implement it in a helper function that fulfills the interface of
sorted
.