返回列表 發帖

排序 - sort() & sorted()

  1. data=input("請輸入多個整數(以空白分隔): ").split(" ")
  2. for i in range(len(data)):    #將串列內容轉換為整數型態
  3.     data[i]=int(data[i])
  4. print("遞增排序: ",end="")
  5. for i in sorted(data):    #sorted()不會真的改變串列的內容
  6.     print(i,end=" ")
  7. print("\n遞減排序: ",end="")
  8. for i in sorted(data,reverse=True):
  9.     print(i,end=" ")
  10. print("\n原始資料: ",end="")
  11. #data.sort()     #sort()會改變串列的內容
  12. for i in data:
  13.     print(i,end=" ")
複製代碼

  1. data=input("請輸入多個整數(以空白分隔): ").split(" ")
  2. for i in range(len(data)):
  3.     data[i]=int(data[i])
  4. print("遞增排序: ",end="")
  5. for i in sorted(data):
  6.     print(i,end=" ")
  7. print("\n遞減排序: ",end="")
  8. for i in sorted(data,reverse=True):
  9.     print(i,end=" ")
  10. print("\n原始資料: ",end="")
  11. for i in data:
  12.     print(i,end=" ")
複製代碼

TOP

  1. data = input("enter a list of numbers (seperate with space in between): ").split(" ")
  2. for i in range(len(data)):
  3.     data[i] = int(data[i])
  4. print("ascending sort: ", end = " ")
  5. for i in sorted(data):
  6.     print(i, end = " ")
  7. print("\ndescending sort: ", end = " ")
  8. for i in sorted(data, reverse = True):
  9.     print(i, end = " ")
  10. print("\noriginal data: ", end = " ")
  11. for i in data:
  12.     print(i, end = " ")
複製代碼

TOP

返回列表