﻿ 分享9个好用的Python技巧 - 鸿网互联

# 分享9个好用的Python技巧

• 1.引言
• 2.Trick 1
• 3.Trick 2
• 4.Trick3
• 5.Trick4
• 6.Trick5
• 7.Trick6
• 8.Trick7
• 9.Trick8
• 10.Trick9
• 11.总结

## 1.引言

iterables的示例包括：

Iterables是一个需要我们牢记的概念，因为接下来我们展示的许多技巧都使用itertools包。

itertools模块提供了一些函数，用于接收Iterable对象，而不仅仅是打印逐个对象。

## 2.Trick 1

```names = ['John', 'Bard', 'Jessica' 'Andres']
lower_names = [name.lower() for name in names]
```

```names = ['John', 'Bard', 'Jessica' 'Andres']
lower_names = {name.lower() for name in names}
```

```names = ['John', 'Bard', 'Jessica' 'Andres']
lower_names = {name:name.lower() for name in names}
```

## 3.Trick 2

```l1 = [1, 2, 3]
l2 = [4, 5, 6]
combinations = []
for e1 in l1:
for e2 in l2:
combinations.append((e1, e2))
```

```combinations = [(e1, e2) for e1 in l1 for e2 in l1]
```

```from itertools import product
l1 = [1, 2, 3]
l2 = [4, 5, 6]
combinatios = product(l1, l2)
```

## 4.Trick3

```from itertools import tee
from typing import Iterable

def window2(iterable: Iterable):
it, offset = tee(iter(iterable))
next(offset)
return zip(it, offset)
l = [1, 2, 3, 4, 5, 6]
dd = window2(l)
for a in dd:
print(a)
```

```(1, 2)
(2, 3)
(3, 4)
(4, 5)
(5, 6)
```

## 5.Trick4

```from dataclasses import dataclass
@dataclass
class Person:
name: str
age: int
```

```person = Person(name='John', age=12, address='nanjing street')
```

dataclass的另一个优点是，默认情况下，会生成特殊方法，如__str__、repr、__eq__等。关于dataclass的更多用法，可以参考官网。

## 6.Trick5

```from typing import NamedTuple
class Coordinate(NamedTuple):
x: int
y: int
```

```coordinate = Coordinate(10, 15)
coordinate.x == coordinate[0] // True
coordinate.y == coordinate[1] // True
```

## 7.Trick6

from dataclasses import dataclass 替换为 from pydantic.dataclasses import dataclass 即可，如下：

```from pydantic.dataclasses import dataclass
@dataclass
class Person:
name: str
age: int
```

## 8.Trick7

```from collections import Counter
l = [1, 1, 2, 3, 4, 4]
frequencys = Counter(l)
print(frequencys[1])    // Ouput: 2
print(frequencys[2])    // Ouput: 1
print(frequencys[2323]) // Ouput: 0
```

Counter也提供了一些其他方法，比如如most_common，用于检索最常见的元素。

## 9.Trick8

```l1 = [1, 2, 3]
l2 = [4, 5, 6]
for (e1, e2) in zip(l1, l2):
f(e1, e2)
```

```l1 = [1, 2, 3]
l2 = [4, 5, 6]
map(f, l1, l2)
```

## 10.Trick9

```from random import choice
l = [1, 2, 3]
random = choice(l)
```

```from random import choices
l = [1, 2, 3, 4, 5]
random_elements = choices(l, k=3)
```

<