I would like to sort the following list using selection sort:
list1 = [(1,2,3),(3,6,4),(4,7,9)]
How can I sort the above by the second element of each tuple (2,6,7) ?
I have the following code for a normal selection sort, but I do now know how to do it with tuples.
def selection_sort(list):
for i in range(len(list)):
mini = min(list[i:])
min_index = list[i:].index(mini)
list[i + min_index] = list[i]
list[i] = mini
You can tell min
to use the second element for comparisons:
mini = min(list[i:], key=lambda l: l[1])
Btw, it's bad to call your variable list
because then you can't use Python's own list
anymore and because you're confusing everyone. Also, you didn't even make it a list but a tuple, preventing the in-place sorting that you're trying.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.