实验目的

实验内容

def f1(a, b): print a, b          # Normal args
def f2(a, *b): print a, b         # Positional varargs
def f3(a, **b): print a, b        # Keyword varargs
def f4(a, *b, **c): print a, b, c   # Mixed modes
def f5(a, b=2, c=3): print a, b, c # Defaults
def f6(a, b=2, *c): print a, b, c    # Defaults and positional varargs

现在测试如下的调用,会产生什么结果?为什么?你认为把不同的匹配方式混合在一起使用是一个好主意吗?你能想到这样的写法在哪里会有用吗?

>>> f1(1, 2)
>>> f1(b=2, a=1)
>>> f2(1, 2, 3)
>>> f3(1, x=2, y=3)
>>> f4(1, 2, 3, x=2, y=3)
>>> f5(1)
>>> f5(1, 4)
>>> f6(1)
>>> f6(1, 3, 4)

思考题

下面的代码用了一个while循环和一个found标记,来在一个2的幂构成的列表中查找2的5次幂。

   1 L = [1, 2, 4, 8, 16, 32, 64]
   2 X = 5
   3 found = i = 0
   4 while not found and i < len(L):
   5     if 2 ** X == L[i]:
   6         found = True
   7     else:
   8         i = i+1
   9 if found:
  10     print 'at index', i
  11 else:
  12     print X, 'not found'

输出

at index 5

这个例子没有使用通常的Python编程技术。我们用如下的步骤来改进它:

  1. 首先,用带else的while循环来消除found标记和最后的if语句。
  2. 然后,用带else的for循环来消除列表下标的使用。
  3. 然后,使用in运算符来完全消除循环的使用。
  4. 最后,使用for循环来生成2的幂构成的列表,而不是把数字以字面常量的形式直接写在代码中。
  5. 更多思考:(1) 你觉得把2**X表达式放在循环的外面能不能改善程序的速度?你怎么实现?(2)Python有一个map(function, list)函数,试着用它来产生2的幂构成的列表。
ch3n2k.com | Copyright (c) 2004-2020 czk.