概要
Pythonで「リストの要素を昇順または降順に並び替える」の動作を確認してみました。以下のページを参考にしました。
実装
以下のファイルを作成しました。
sample.py
numlist = [84, 75, 92, 90, 78]
newnumlist = sorted(numlist)
print("Before:", numlist)
print("After: ", newnumlist)
colorlist = ["Blue", "Red", "Green", "White", "Black"]
newcolorlist = sorted(colorlist)
print("Before:", colorlist)
print("After: ", newcolorlist)
numlist = [5, 3.14, 4.78, 4]
newnumlist = sorted(numlist)
print(newnumlist)
mylist = ["80", 75, 45, "68"]
#newmylist = sorted(mylist)
colorlist = ["Blue", "Red", "Green", "White", "Black"]
upcolorlist = sorted(colorlist)
downcolorlist = sorted(colorlist, reverse=True)
print("Orig:", colorlist)
print("ASC: ", upcolorlist)
print("DESC:", downcolorlist)
animallist = ["Cat", "monkey", "bear", "Sheep", "cow"]
sortlist = sorted(animallist)
lowersortlist = sorted(animallist, key=str.lower)
print(animallist)
print(sortlist)
print(lowersortlist)
以下のコマンドを実行しました。
$ python3 sample.py
Before: [84, 75, 92, 90, 78]
After: [75, 78, 84, 90, 92]
Before: ['Blue', 'Red', 'Green', 'White', 'Black']
After: ['Black', 'Blue', 'Green', 'Red', 'White']
[3.14, 4, 4.78, 5]
Orig: ['Blue', 'Red', 'Green', 'White', 'Black']
ASC: ['Black', 'Blue', 'Green', 'Red', 'White']
DESC: ['White', 'Red', 'Green', 'Blue', 'Black']
['Cat', 'monkey', 'bear', 'Sheep', 'cow']
['Cat', 'Sheep', 'bear', 'cow', 'monkey']
['bear', 'Cat', 'cow', 'monkey', 'Sheep']
まとめ
何かの役に立てばと。