python基礎知識-列表的排序問題
阿新 • • 發佈:2018-03-12
OS eve pri cci 問題 print 沒有 div err
def main(): f=[‘orange‘,‘zoo‘,‘apple‘,‘internationalization‘,‘blueberry‘] #python 內置的排序方式默認為升序(從小到大) #如果想要降序 用reverse參數來制定 #python中的函數幾乎沒有副作用的函數 #調用函數之後不會影響傳入的參數 f2 = sorted (f,reverse=True) print(f) print(f2) f.reverse() f3=(reversed(f)) print(f3) f4=sorted(f,key=str_len,reverse=True) print(f4) 結果: [‘orange‘, ‘zoo‘, ‘apple‘, ‘internationalization‘, ‘blueberry‘] [‘zoo‘, ‘orange‘, ‘internationalization‘, ‘blueberry‘, ‘apple‘] <list_reverseiterator object at 0x000000000259E9B0> [‘internationalization‘, ‘blueberry‘, ‘orange‘, ‘apple‘, ‘zoo‘]
如:fibonacci函數
def fib1(n): d=[1,1] for num in range (2,n): val=d[num-1]+d[num-2] d.append(val) print(d) print(d[::2]) print(d[-1:-3:-1]) d.reverse() print(d) if __name__ == ‘__main__‘: fib1(20) 結果: [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765] [1, 2, 5, 13, 34, 89, 233, 610, 1597, 4181] [6765, 4181] [6765, 4181, 2584, 1597, 987, 610, 377, 233, 144, 89, 55, 34, 21, 13, 8, 5, 3, 2, 1, 1]
python基礎知識-列表的排序問題