python语言做法_python学习笔记(十六)
## Python語言進階
### 重要知識點
- 生成式(推導式)的用法
```Python
prices = {
'AAPL': 191.88,
'GOOG': 1186.96,
'IBM': 149.24,
'ORCL': 48.44,
'ACN': 166.89,
'FB': 208.09,
'SYMC': 21.29
}
# 用股票價格大于100元的股票構造一個新的字典
prices2 = {key: value for key, value in prices.items() if value > 100}
print(prices2)
```
> 說明:生成式(推導式)可以用來生成列表、集合和字典。
- 嵌套的列表的坑
```Python
names = ['關羽', '張飛', '趙云', '馬超', '黃忠']
courses = ['語文', '數學', '英語']
# 錄入五個學生三門課程的成績
# 錯誤 - 參考http://pythontutor.com/visualize.html#mode=edit
# scores = [[None] * len(courses)] * len(names)
scores = [[None] * len(courses) for _ in range(len(names))]
for row, name in enumerate(names):
for col, course in enumerate(courses):
scores[row][col] = float(input(f'請輸入{name}的{course}成績: '))
print(scores)
```
[Python Tutor](http://pythontutor.com/) - VISUALIZE CODE AND GET LIVE HELP
- `heapq`模塊(堆排序)
```Python
"""
從列表中找出最大的或最小的N個元素
堆結構(大根堆/小根堆)
"""
import heapq
list1 = [34, 25, 12, 99, 87, 63, 58, 78, 88, 92]
list2 = [
{'name': 'IBM', 'shares': 100, 'price': 91.1},
{'name': 'AAPL', 'shares': 50, 'price': 543.22},
{'name': 'FB', 'shares': 200, 'price': 21.09},
{'name': 'HPQ', 'shares': 35, 'price': 31.75},
{'name': 'YHOO', 'shares': 45, 'price': 16.35},
{'name': 'ACME', 'shares': 75, 'price': 115.65}
]
print(heapq.nlargest(3, list1))
print(heapq.nsmallest(3, list1))
print(heapq.nlargest(2, list2, key=lambda x: x['price']))
print(heapq.nlargest(2, list2, key=lambda x: x['shares']))
```
- `itertools`模塊
```Python
"""
迭代工具模塊
"""
import itertools
# 產生ABCD的全排列
itertools.permutations('ABCD')
# 產生ABCDE的五選三組合
itertools.combinations('ABCDE', 3)
# 產生ABCD和123的笛卡爾積
itertools.product('ABCD', '123')
# 產生ABC的無限循環序列
itertools.cycle(('A', 'B', 'C'))
```
- `collections`模塊
常用的工具類:
- `namedtuple`:命令元組,它是一個類工廠,接受類型的名稱和屬性列表來創建一個類。
- `deque`:雙端隊列,是列表的替代實現。Python中的列表底層是基于數組來實現的,而deque底層是雙向鏈表,因此當你需要在頭尾添加和刪除元素是,deque會表現出更好的性能,漸近時間復雜度為$O(1)$。
- `Counter`:`dict`的子類,鍵是元素,值是元素的計數,它的`most_common()`方法可以幫助我們獲取出現頻率最高的元素。`Counter`和`dict`的繼承關系我認為是值得商榷的,按照CARP原則,`Counter`跟`dict`的關系應該設計為關聯關系更為合理。
- `OrderedDict`:`dict`的子類,它記錄了鍵值對插入的順序,看起來既有字典的行為,也有鏈表的行為。
- `defaultdict`:類似于字典類型,但是可以通過默認的工廠函數來獲得鍵對應的默認值,相比字典中的`setdefault()`方法,這種做法更加高效。
```Python
"""
找出序列中出現次數最多的元素
"""
from collections import Counter
words = [
'look', 'into', 'my', 'eyes', 'look', 'into', 'my', 'eyes',
'the', 'eyes', 'the', 'eyes', 'the', 'eyes', 'not', 'around',
'the', 'eyes', "don't", 'look', 'around', 'the', 'eyes',
'look', 'into', 'my', 'eyes', "you're", 'under'
]
counter = Counter(words)
print(counter.most_common(3))
```
### 數據結構和算法
- 算法:解決問題的方法和步驟
- 評價算法的好壞:漸近時間復雜度和漸近空間復雜度。
- 漸近時間復雜度的大O標記:
- - 常量時間復雜度 - 布隆過濾器 / 哈希存儲
- - 對數時間復雜度 - 折半查找(二分查找)
- - 線性時間復雜度 - 順序查找 / 計數排序
- - 對數線性時間復雜度 - 高級排序算法(歸并排序、快速排序)
- - 平方時間復雜度 - 簡單排序算法(選擇排序、插入排序、冒泡排序)
- - 立方時間復雜度 - Floyd算法 / 矩陣乘法運算
- - 幾何級數時間復雜度 - 漢諾塔
- - 階乘時間復雜度 - 旅行經銷商問題 - NPC


- 排序算法(選擇、冒泡和歸并)和查找算法(順序和折半)
```Python
def select_sort(items, comp=lambda x, y: x < y):
"""簡單選擇排序"""
items = items[:]
for i in range(len(items) - 1):
min_index = i
for j in range(i + 1, len(items)):
if comp(items[j], items[min_index]):
min_index = j
items[i], items[min_index] = items[min_index], items[i]
return items
```
```Python
def bubble_sort(items, comp=lambda x, y: x > y):
"""冒泡排序"""
items = items[:]
for i in range(len(items) - 1):
swapped = False
for j in range(len(items) - 1 - i):
if comp(items[j], items[j + 1]):
items[j], items[j + 1] = items[j + 1], items[j]
swapped = True
if not swapped:
break
return items
```
```Python
def bubble_sort(items, comp=lambda x, y: x > y):
"""攪拌排序(冒泡排序升級版)"""
items = items[:]
for i in range(len(items) - 1):
swapped = False
for j in range(len(items) - 1 - i):
if comp(items[j], items[j + 1]):
items[j], items[j + 1] = items[j + 1], items[j]
swapped = True
if swapped:
swapped = False
for j in range(len(items) - 2 - i, i, -1):
if comp(items[j - 1], items[j]):
items[j], items[j - 1] = items[j - 1], items[j]
swapped = True
if not swapped:
break
return items
```
```Python
def merge(items1, items2, comp=lambda x, y: x < y):
"""合并(將兩個有序的列表合并成一個有序的列表)"""
items = []
index1, index2 = 0, 0
while index1 < len(items1) and index2 < len(items2):
if comp(items1[index1], items2[index2]):
items.append(items1[index1])
index1 += 1
else:
items.append(items2[index2])
index2 += 1
items += items1[index1:]
items += items2[index2:]
return items
def merge_sort(items, comp=lambda x, y: x < y):
return _merge_sort(list(items), comp)
def _merge_sort(items, comp):
"""歸并排序"""
if len(items) < 2:
return items
mid = len(items) // 2
left = _merge_sort(items[:mid], comp)
right = _merge_sort(items[mid:], comp)
return merge(left, right, comp)
```
```Python
def seq_search(items, key):
"""順序查找"""
for index, item in enumerate(items):
if item == key:
return index
return -1
```
```Python
def bin_search(items, key):
"""折半查找"""
start, end = 0, len(items) - 1
while start <= end:
mid = (start + end) // 2
if key > items[mid]:
start = mid + 1
elif key < items[mid]:
end = mid - 1
else:
return mid
return -1
```
總結
以上是生活随笔為你收集整理的python语言做法_python学习笔记(十六)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python常用库教程_这几个pytho
- 下一篇: mysql数据库连接jar_mysql数