### 1.”夹数”

```def clamp_number(num,a,b):
return max(min(num, max(a,b)),min(a,b)) ```

```>> clamp_number(2,3,10)
3
>> clamp_number(7,3,10)
7
>> clamp_number(124,3,10)
10 ```

## 2.键值映射

```def map_values(obj, fn):
ret = {}
for key in obj.keys():
ret[key] = fn(obj[key])
return ret ```

```>>> users = {
...   'fred': { 'user': 'fred', 'age': 40 },
...   'pebbles': { 'user': 'pebbles', 'age': 1 }
... }
>>> map_values(users, lambda u : u['age'])
{'fred': 40, 'pebbles': 1}
>>> map_values(users, lambda u : u['age']+1)
{'fred': 41, 'pebbles': 2}       ```

## 3.大小写转换

upper_rest参数：设定是否将除首字母外的其他字母大小写转换。

```def decapitalize(s, upper_rest=False):
return s[:1].lower() + (s[1:].upper() if upper_rest else s[1:])```

```>>> decapitalize('FooBar')
'fooBar'
>>> decapitalize('FooBar', True)
'fOOBAR' ```

## 4.同键求和

```def sum_by(lst, fn):
return sum(map(fn,lst)) ```

```>>> sum_by([{ 'n': 4 }, { 'n': 2 }, { 'n': 8 }], lambda v : v['n'])
14  ```

## 5.一行代码求出现次数

```def count_occurrences(lst, val):
return len([x for x in lst if x == val and type(x) == type(val)])```

```>>> count_occurrences([1, 1, 2, 1, 2, 3], 1)
3 ```

​Python实用宝典 (pythondict.com)