首页 > 代码库 > Python外壳:代码结构
Python外壳:代码结构
使用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 值的整型 / 浮点型、空字符串( ‘‘)、空列表( [])、
空元组( (,))、空字典( {})、空集合( 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外壳:代码结构