標籤:變數 end 元組 ora 通過 print 資料 letters 用兩個
使用zip()並行迭代
days = [‘Monday‘, ‘Tuesday‘, ‘Wednesday‘]
>>> fruits = [‘banana‘, ‘orange‘, ‘peach‘]
>>> drinks = [‘coffee‘, ‘tea‘, ‘beer‘]
>>> desserts = [‘tiramisu‘, ‘ice cream‘, ‘pie‘, ‘pudding‘]
>>> for day, fruit, drink, dessert in zip(days, fruits, drinks, desserts):
... print(day, ": drink", drink, "- eat", fruit, "- enjoy", dessert)
...
Monday : drink coffee - eat banana - enjoy tiramisu
Tuesday : drink tea - eat orange - enjoy ice cream
Wednesday : drink beer - eat peach - enjoy pie
english = ‘Monday‘, ‘Tuesday‘, ‘Wednesday‘
>>> french = ‘Lundi‘, ‘Mardi‘, ‘Mercredi‘
現在使用 zip() 函數配對兩個元組。函數的傳回值既不是元組也不是列表,而是一個整合
Python外殼:代碼結構 | 71
在一起的可迭代變數:
list( zip(english, french) )
[(‘Monday‘, ‘Lundi‘), (‘Tuesday‘, ‘Mardi‘), (‘Wednesday‘, ‘Mercredi‘)]
配合 dict() 函數和 zip() 函數的傳回值就可以得到一本微型的英法詞典:
>>> dict( zip(english, french) )
{‘Monday‘: ‘Lundi‘, ‘Tuesday‘: ‘Mardi‘, ‘Wednesday‘: ‘Mercredi‘}
[ expression for item in iterable ]
下面的例子將通過列表推導建立一個整數列表:
>>> number_list = [number for number in range(1,6)]
>>> number_list
[1, 2, 3, 4, 5]
rows = range(1,4)
>>> cols = range(1,3)
>>> cells = [(row, col) for row in rows for col in cols]
>>> for cell in cells:
... print(cell)
a_list = [number for number in range(1,6) if number % 2 == 1]
字典推導式:
>>> word = ‘letters‘
>>> letter_counts = {letter: word.count(letter) for letter in set(word)}
>>> letter_counts
{‘t‘: 2, ‘l‘: 1, ‘e‘: 2, ‘r‘: 1, ‘s‘: 1}
集合推導式:
a_set = {number for number in range(1,6) if number % 3 == 1}
>>> a_set
{1, 4}
產生器推導式:
一個產生器只能運行一次。列表、集合、字串和字典都儲存在記憶體中,但
是產生器僅在運行中產生值, 不會被存下來,所以不能重新使用或者備份一
個產生器。
圓括弧之間的是產生器推導式
number_thing = (number for number in range(1, 6))
for number in number_thing:
... print(number)
0 值的整型 / 浮點型、Null 字元串( ‘‘)、空列表( [])、
空元組( (,))、空字典( {})、空集合( set())都等價於 False,但是不等於 None
def is_none(thing):
... if thing is None:
... print("It‘s None")
... elif thing:
... print("It‘s True")
... else:
... print("It‘s False")
預設參數值在函數被定義時已經計算出來,而不是在程式運行時。 Python 程
序員經常犯的一個錯誤是把可變的資料類型( 例如列表或者字典)當作預設
參數值。
def buggy(arg, result=[]):
... result.append(arg)
... print(result)
...
>>> buggy(‘a‘)
[‘a‘]
>>> buggy(‘b‘) # expect [‘b‘]
[‘a‘, ‘b‘]
def works(arg):
... result = []
... result.append(arg)
... return result
...
>>> works(‘a‘)
[‘a‘]
>>> works(‘b‘)
[‘b‘]
def nonbuggy(arg, result=None):
... if result is None:
... result = []
... result.append(arg)
... print(result)
...
>>> nonbuggy(‘a‘)
[‘a‘]
>>> nonbuggy(‘b‘)
[‘b‘]
使用*收集位置參數:
當參數被用在函數內部時, 星號將一組可變數量的位置參數集合成參數值的元組
給函數傳入的所有參數都會以元組的形式返回輸出:
def print_args(*args):
... print(‘Positional argument tuple:‘, args)
print_args(3, 2, 1, ‘wait!‘, ‘uh...‘)
Positional argument tuple: (3, 2, 1, ‘wait!‘, ‘uh...‘)
def print_more(required1, required2, *args):
... print(‘Need this one:‘, required1)
... print(‘Need this one too:‘, required2)
... print(‘All the rest:‘, args)
...
>>> print_more(‘cap‘, ‘gloves‘, ‘scarf‘, ‘monocle‘, ‘mustache wax‘)
Need this one: cap
Need this one too: gloves
All the rest: (‘scarf‘, ‘monocle‘, ‘mustache wax‘)
使用**收集關鍵字參數:
使用兩個星號可以將參數收集到一個字典中,參數的名字是字典的鍵,對應參數的值是字
典的值
def print_kwargs(**kwargs):
... print(‘Keyword arguments:‘, kwargs)
print_kwargs(wine=‘merlot‘, entree=‘mutton‘, dessert=‘macaroon‘)
Keyword arguments: {‘dessert‘: ‘macaroon‘, ‘wine‘: ‘merlot‘, ‘entree‘: ‘mutton‘}
閉包:
內建函式可以看作一個閉包。閉包是一個可以由另一個函數動態產生的函數, 並且可以改
變和儲存函數外建立的變數的值
def knights2(saying):
... def inner2():
... return "We are the knights who say: ‘%s‘" % saying
... return inner2
將每個單詞的首字母變為大寫:word.capitalize()
Python 提供了兩個擷取命名空間內容的函數:
? locals() 返回一個局部命名空間內容的字典;
? globals() 返回一個全域命名空間內容的字典。
Python外殼:代碼結構