How to implement Selection Sort within a list?

筅森魡賤 提交于 2019-12-02 02:59:01

Python lists come with a sort method already. You can simply call it, specifying a key argument to determine how to sort.

def print_list(table):
    for line in table:
       print(str(line[0]) + " kms, $" + str(line[1]))

with open(input("Enter file name: ")) as f:
    table = []
    for line in f:
        line = line.rstrip().split(",")
        line[0] = int(line[0])
        line[1] = float(line[1])
        table.append(line)

    table.sort(key=lambda line: line[1])
    print_list(table)

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.

Is it absolutely necessary to implement selection sort? I would go with sorted:

PrintList(sorted(table, key = lambda x: x[1]))

where

key = lambda x: x[1]

instructs sorted to use the value of the element with index 1 (price) to compare your objects.

after your for-loop:

sorted_table = sorted(table, key=lambda row: row[1], reverse=True)

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:

from operator import itemgetter
sorted_table = sorted(table, key=itemgetter(1), reverse=True)

For more on python sorting, see: https://wiki.python.org/moin/HowTo/Sorting

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!