這邊來說說我解題時發現的一點有趣的事,另外也發現有 [Defaultdict](https://hackmd.io/@sudo-s/Hk5ak9Q11g) 這個便利的工具 `好耶.jpg`
---
### 字典
字典排序後仍可以單獨取 key 值出來用
(字典本身可以只取 key,也有 `<dict_name>.keys()` 可以用)
```python
from collections import defaultdict
ls = [0, 4, 5, 3, 7, 6, 8, 1, 2, 9]
dd = defaultdict(list)
for _ in sorted(ls):
dd[_ & 1].append(_)
print('Sorted Dict:')
for _ in sorted(dd):
print(_, end=' ')
```
```shell
Sorted Dict:
0 1
```
## 列舉
index 是遞增,但若是使用列舉,因為每個元素都是集合(set),通常用會兩個參數來 unpack
```python
print('Enum Unpack:')
for k, v in enumerate(ls):
print(k, end=' ')
```
```shell
Enum Unpack:
0 1 2 3 4 5 6 7 8 9
```
```shell
Enum Datas:
{
(0, 0),
(1, 4),
(2, 5),
...
}
```
另一種更簡潔的寫法是將列舉轉為字典,這樣就可以只取 key 值,而不訪問資料
```python
print('Enum to Dict:')
for _ in dict(enumerate(ls)):
print(_, end=' ')
```
```shell
Enum to Dict:
0 1 2 3 4 5 6 7 8 9
```
```shell
Enum Datas:
{
0: 0,
1: 4,
2: 5,
...
}
```