[英]How do I make my button, sort the numbers inputted by a user in a descending way, as it only does ascending
所以我讓我的代碼使用 GUI 進行選擇排序,並想添加一個“降序排序”按鈕,它將數字從最大到最小排序。 謝謝請幫忙。 這是一個學校項目,因此功能更長等。
#Variable of the array
A = []
#Add Function
def add():
global label_result
newNumber = int(passwordEntry.get())
A.append(newNumber)
label_result = tk.Label(master, text=str(A))
label_result.grid(row=3, column=0, columnspan=2)
#Sort Function
def sort(A):
#Sets the comparison number - The book from demonstration
for i in range(len(A)):
# Find the minimum element in remaining
# unsorted array
minimum = i
#The septre from demonstration (what its being compared to)
for j in range(i+1, len(A)):
#The stop sign (the lowest number out of the remainding numbers)
if A[minimum] > A[j]:
minimum = j
# Swap the found minimum element with
# the first element
A[i], A[minimum] = A[minimum], A[i]
label_msg['text'] = "Sorted"
label_result['text'] = str(A)
master = tk.Tk()
master.title("Dans Selection Sort")
passwordEntry = tk.Entry(master)
passwordEntry.grid(row=0, column=1)
tk.Label(master, text='Enter Number: ', font='bold',).grid(row=0, column=0)
tk.Button(master, text='Add to Array', command=add).grid(row=1, column=0)
#lambda allows you to call a function with parameter.
tk.Button(master, text='Sort Ascending', command=lambda: sort(A)).grid(row=1, column=1)
tk.Button(master, text='Sort Descending', command=lambda: sort(A)).grid(row=1, column=2)
label_msg = tk.Label(master, text='')
label_msg.grid(row=2, column=0, columnspan=2)```
大於 = lambda a, b: a > b
def sort(A, compare):
...
if compare(A[minimum], A[j]):
...
更改您的比較 function 以獲得不同的排序。
def sort(A, reverse=False):
...
if (A[minimum] < A[j] and not reverse) or (not A[minimum] < A[j] and reverse):
...
sort(A)
A = A[::-1]
使用list.sort(reverse=True)
。
使用list = sorted(list, reverse=True)
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.