簡體   English   中英

我如何添加另一個簡單的 function 以添加兩個選項以按數字升序和降序對此代碼進行排序?

[英]how do i add another simple function to add two more options to sort this code numerically ascending and descending?

感謝所有幫助過的人。 由於一條評論指出了我的錯誤,我已經使代碼正常工作,我現在想添加一個 function 以獲得另外 2 個選項,以按數字升序和降序對這段代碼進行排序

fruit= [["apples", 5], ["pears", 10], ["oranges", 6], ["bananas", 12], ["grapes", 100]]

items= [["cars",3], ["sheets",5], ["bananas",8], ["bridges",17], ["roads",0], ["doors",1]]

colours= [["blue",1], ["black",7], ["orange",13], ["yellow",2], ["red",8], ["blue",5]]


merge = fruit + items + colours
result = set(
    (item, sum(quantity for label, quantity in merge if label == item))
    for item, _ in merge
)

print ()        
print ("SHOW DATA")
print ()

print ("fruit :", fruit)
print ("items :", items)
print ("colours :", colours)

print ()
print ("WHICH ORDER?")
print ()

print ("1 = Alphabetically Ascending")
print ("2 = Alphabetically Descending")
print ("")
SortOrder = int(input ("Enter the sort order you prefer for the merged data >"))

if (SortOrder == 1):
    lists = sorted(result)
    for l in lists:
       print(l)

elif (SortOrder == 2):
    lists = sorted(result, reverse=True)
    for l in lists:
       print(l)

集合沒有.sort()方法,您需要使用sorted()方法,並且循環遍歷未定義的lists

這是一個解決方案:

if (SortOrder == 1):
    lists = sorted(result)
    for l in lists:
       print(l)
elif (SortOrder == 2):
    lists = sorted(result, reverse=True)
    for l in lists:
       print(l)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM