Python Tutorial 第二堂(2)容器、流程、for 包含式
Python Tutorial 第二堂(1)數值與字串型態 << 前情 此文件已有新版,詳見〈Python 3 Tutorial 第二堂(3)容器、流程、for 包含式〉。 想想你平時撰寫的一些應用程式,大部份是在處理一組資料,Python 對管理資料用的容器(Container)型態,在語法上提供直接支援,加上 Python 支援的容器型態有 list 型態
>>> [0] * 10 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] >>> ', '.join(['justin', 'caterpillar', 'openhome']) 'justin, caterpillar, openhome' >>> list('justin') ['j', 'u', 's', 't', 'i', 'n'] >>> set 型態
>>> admins = {'Justin', 'caterpillar'} # 建立 set >>> users = {'momor', 'hamini', 'Justin'} >>> 'Justin' in admins # 是否在站長群? True >>> admins & users # 同時是站長群也是使用者群的? {'Justin'} >>> admins | users # 是站長群或是使用者群的? {'hamini', 'caterpillar', 'Justin', 'momor'} >>> admins - users # 站長群但不使用者群的? {'caterpillar'} >>> admins ^ users # XOR {'hamini', 'caterpillar', 'momor'} >>> admins > users # ∈ False >>> admins < users False >>> dict 型態鍵(Key)值(Value)對應的物件,鍵物件必須是 hashable。以下是一些操作示範: >>> passwords = {'Justin' : 123456, 'caterpillar' : 933933} >>> passwords['Justin'] 123456 >>> passwords['Hamimi'] = 970221 # 增加一對鍵值 >>> passwords {'caterpillar': 933933, 'Hamimi': 970221, 'Justin': 123456} >>> del passwords['caterpillar'] # 刪除一對鍵值 >>> passwords {'Hamimi': 970221, 'Justin': 123456} >>> passwords.items() [('Hamimi', 970221), ('Justin', 123456)] >>> passwords.keys() ['Hamimi', 'Justin'] >>> passwords.values() [970221, 123456] >>> 使用 >>> passwords.get('openhome', '000000') '000000' >>> passwords['openhome'] Traceback (most recent call last): File "", line 1, in KeyError: 'openhome' >>> tuple 型態
(在靜態定型的 Haskell 語言中,Tuple 更具效用,因為 Tuple 中的元素型態就組成了一個新的但未命名的型態。) 練習 3:Python 互動模式與直譯器指令 開啟一個終端機,鍵入
離開互動模式後,直接鍵入以下指令會看到什麼?
The Zen of Python, by Tim Peters Beautiful is better than ugly. Explicit is better than implicit. Simple is better than complex. Complex is better than complicated. Flat is better than nested. Sparse is better than dense. Readability counts. Special cases aren't special enough to break the rules. Although practicality beats purity. Errors should never pass silently. Unless explicitly silenced. In the face of ambiguity, refuse the temptation to guess. There should be one-- and preferably only one --obvious way to do it. Although that way may not be obvious at first unless you're Dutch. Now is better than never. Although never is often better than *right* now. If the implementation is hard to explain, it's a bad idea. If the implementation is easy to explain, it may be a good idea. Namespaces are one honking great idea -- let's do more of those! if、for 與 while流程語法中最簡單的 from sys import argv if len(argv) > 1: print 'Hello, ' + argv[1] else: print 'Hello, Guest' 在 Python 中,使用 from sys import argv print 'Hello, ' + (argv[1] if len(argv) > 1 else 'Guest') Python 中的 numbers = [10, 20, 30] squares = [] for number in numbers: squares.append(number ** 2) print squares 至於 print 'Enter two numbers...' m = int(raw_input('Number 1: ')) n = int(raw_input('Number 2: ')) while n != 0: r = m % n m = n n = r print 'GCD: {0}'.format(m) 回頭看看想這個範例: numbers = [10, 20, 30] squares = [] for number in numbers: squares.append(number ** 2) print squares 將某 numbers = [10, 20, 30] print [number ** 2 for number in numbers] 這樣的寫法顯然簡潔多了。 numbers = [11, 2, 45, 1, 6, 3, 7, 8, 9] odd_numbers = [] for number in numbers: if number % 2 != 0: odd_numbers.append(number) print odd_numbers 使用 numbers = [11, 2, 45, 1, 6, 3, 7, 8, 9] print [number for number in numbers if number % 2 != 0]
lts = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] print [ele for lt in lts for ele in lt] 當你使用 >>> {name for name in ['caterpillar', 'Justin', 'caterpillar', 'openhome']} set(['caterpillar', 'Justin', 'openhome']) >>> 也可以建立 >>> {name : passwd for name, passwd in zip(names, passwds)} {'caterpillar': 123456, 'Justin': 13579, 'openhome': 987654} >>> 上例中的 (有些人剛接觸 Python 時,不太習慣 練習 4:使用 在 LAB 檔案中,有個 exercises\exercise4\exercise4-1.py,內容如下: numbers = [] for number in range(20): numbers.append(str(number)) print ", ".join(numbers) 請試著使用 (如果想挑戰比較難的練習,可試著使用 |
cytseng
10/31
作者你好, 這篇文章(Python 3 Tutorial 第二堂(3)容器、流程、for 包含式)裡有 bug, 都在 if, for 與 while 裡
1. print('Hello, ', argv[1]) 應該是 print('Hello,' + argue[1])
2, print('Hello, ', argv[1] if len(argv) > 1 else 'Guest') 應該是 print('Hello,' + argv[1] if len(argv) > 1 else 'Guest')