Python 简化函数调用的3种技巧-Python 实用宝典

# Python 简化函数调用的3种技巧

```def sum_four(a, b, c, d):
return a + b + c + d```

```>>> a, b, c = 1, 2, 3

>>> sum_four(a=a, b=b, c=c, d=1)
7

>>> sum_four(a=a, b=b, c=c, d=2)
8

>>> sum_four(a=a, b=b, c=c, d=3)
9

>>> sum_four(a=a, b=b, c=c, d=4)
10```

```>>> list(map(sum_four, [(1, 2, 3, 4)]))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: sum_four() missing 3 required positional arguments: 'b', 'c', and 'd'```

## 方案1: itertools.starmap

```>>> import itertools
>>> list(itertools.starmap(sum_four, [(1, 2, 3, 4)]))
[10]```

```>>> import itertools

>>> ds = [1, 2, 3, 4]

>>> items = ((a, b, c, d) for d in ds)

>>> list(items)
[(1, 2, 3, 1), (1, 2, 3, 2), (1, 2, 3, 3), (1, 2, 3, 4)]

>>> list(itertools.starmap(sum_four, items))
[7, 8, 9, 10]```

## 方案2: functools.partial

```>>> import functools
>>> partial_sum_four = functools.partial(sum_four, a, b, c)
>>> partial_sum_four(3)
9
>>> # 这样就可以使用map函数了：
>>> list(map(partial_sum_four, ds))
[7, 8, 9, 10]```

## 方案3: itertools.repeat()

```>>> list(map(sum_four, [1, 1, 1, 1], [2, 2, 2, 2], [3, 3, 3, 3], [1,2,3,4]))
[7, 8, 9, 10]```

itertools.repeat() 函数能够根据参数产生一个迭代器，该迭代器一次又一次返回对象。不指定times参数，它将无限期运行。

```>>> import itertools
>>> list(map(sum_four, itertools.repeat(a), itertools.repeat(b), itertools.repeat(c), ds))
[7, 8, 9, 10]```

​Python实用宝典 ( pythondict.com )