告別枯燥,60秒學會一個Python小例子。
奔著此出發點,我在過去1個月,將平時經常使用的代碼段換為小例子,分享出來後受到大家的喜歡。
今天我完整梳理一遍,總結到這裡。很感謝這段時間,有3個小夥伴為此庫所做出的貢獻。
一、基本操作
1 鏈式比較
<code>i = 3print(1 < i < 3) # Falseprint(1 < i <= 3) # True/<code>
2 不用else和if實現計算器
<code>from operator import *def calculator(a, b, k):
return { '+': add, '-': sub, '*': mul,
'/': truediv, '**': pow }[k](a, b)calculator(1, 2, '+')
# 3calculator(3, 4, '**')
# 81/<code>
3 函數鏈
<code>from operator import (add, sub)def add_or_sub(a, b, oper):
return (add if oper == '+' else sub)
(a, b)add_or_sub(1, 2, '-')
# -1/<code>
4 求字符串的字節長度
<code>def str_byte_len(mystr): return (len(mystr.encode('utf-8')))str_byte_len('i love python')
# 13(個字節)str_byte_len('字符')
# 6(個字節)/<code>
5 尋找第n次出現位置
<code>def search_n(s, c, n): size = 0 for i, x in enumerate(s):
if x == c: size += 1
if size == n: return i
return -1print(search_n("fdasadfadf", "a", 3))
# 結果為7,正確print(search_n("fdasadfadf", "a", 30))
# 結果為-1,正確/<code>
6 去掉最高最低求平均
<code>def score_mean(lst): lst.sort() lst2=lst[1:(len(lst)-1)]
return round((sum(lst2)/len(lst2)),2)score_mean([9.1, 9.0,8.1, 9.7, 19,8.2, 8.6,9.8]) # 9.07/<code>
7 交換元素
<code>def swap(a, b): return b, aswap(1, 0) # (0,1)/<code>
三、基礎算法
1 二分搜索
<code>
def binarySearch(arr, left, right, x): while left <= right:
mid = int(left + (right - left) / 2);
# 找到中間位置。
求中點寫成(left+right)/2更容易溢出,所以不建議這樣寫
# 檢查x是否出現在位置mid
if arr[mid] == x: print('found %d 在索引位置%d 處' %(x,mid))
return mid
# 假如x更大,則不可能出現在左半部分
elif arr[mid] < x: left = mid + 1 #搜索區間變為[mid+1,right]
print('區間縮小為[%d,%d]' %(mid+1,right))
elif xright = mid - 1 #搜索區間變為[left,mid-1] /<code>
print('區間縮小為[%d,%d]' %(left,mid-1)) return -1
2 距離矩陣
<code>x,y = mgrid[0:5,0:5]list(map(lambda xe,ye: [(ex,ey) for ex, ey in zip(xe, ye)], x,y))
[[(0, 0), (0, 1), (0, 2), (0, 3), (0, 4)], [(1, 0), (1, 1), (1, 2), (1, 3), (1, 4)],
[(2, 0), (2, 1), (2, 2), (2, 3), (2, 4)], [(3, 0), (3, 1), (3, 2), (3, 3), (3, 4)],
[(4, 0), (4, 1), (4, 2), (4, 3), (4, 4)]]/<code>
三、列表
1 打印乘法表
<code>
for i in range(1,10):
for j in range(1,i+1):
print('{0}*{1}={2}'.format(j,i,j*i),end="\\t")
print()/<code>
結果:
1*1=11*2=2 2*2=41*3=3 2*3=6 3*3=91*4=4 2*4=8 3*4=12 4*4=161*5=5 2*5=10 3*5=15 4*5=20 5*5=251*6=6 2*6=12 3*6=18 4*6=24 5*6=30 6*6=361*7=7 2*7=14 3*7=21 4*7=28 5*7=35 6*7=42 7*7=491*8=8 2*8=16 3*8=24 4*8=32 5*8=40 6*8=48 7*8=56 8*8=641*9=9 2*9=18 3*9=27 4*9=36 5*9=45 6*9=54 7*9=63 8*9=72 9*9=81
2 嵌套數組完全展開
<code>from collections.abc import *def flatten(input_arr, output_arr=None):
if output_arr is None: output_arr = [] for ele in input_arr:
if isinstance(ele, Iterable):
# 判斷ele是否可迭代
flatten(ele, output_arr)
# 尾數遞歸 else:
output_arr.append(ele)
# 產生結果 return output_arrflatten([[1,2,3],[4,5]], [6,7])
# [6, 7, 1, 2, 3, 4, 5]/<code>
3 將list等分為子組
<code>from math import ceildef divide(lst, size): if size <= 0:
return [lst] return [lst[i * size:(i+1)*size] for i in range(0, ceil(len(lst) / size))]
r = divide([1, 3, 5, 7, 9], 2) # [[1, 3], [5, 7], [9]]/<code>
4 生成fibonacci序列前n項
<code>def fibonacci(n): if n <= 1: return [1] fib = [1, 1] while len(fib) < n:
fib.append(fib[len(fib) - 1] + fib[len(fib) - 2]) return fibfibonacci(5) # [1, 1, 2, 3, 5]/<code>
5 過濾掉各種空值
<code>def filter_false(lst): return list(filter(bool, lst))filter_false([None, 0, False, '', [], 'ok', [1, 2]])# ['ok', [1, 2]]/<code>
6 返回列表頭元素
<code>def head(lst): return lst[0] if len(lst) > 0 else Nonehead([]) # Nonehead([3, 4, 1]) # 3/<code>
7 返回列表尾元素
<code>def tail(lst): return lst[-1] if len(lst) > 0 else Noneprint(tail([])) # Noneprint(tail([3, 4, 1])) # 1/<code>
8 對象轉換為可迭代類型
<code>from collections.abc import Iterabledef cast_iterable(val):
return val if isinstance(val, Iterable) else [val]cast_iterable('foo')
# foocast_iterable(12)# [12]cast_iterable({'foo': 12})# {'foo': 12}/<code>
9 求更長列表
<code>def max_length(*lst): return max(*lst, key=lambda
v: len(v))r = max_length([1, 2, 3], [4, 5, 6, 7], [8])# [4, 5, 6, 7]/<code>
10 出現最多元素
<code>def max_frequency(lst):
return max(lst, default='列表為空',
key=lambda v: lst.count(v))lst = [1, 3, 3, 2, 1, 1, 2]max_frequency(lst) # 1/<code>
11 求多個列表的最大值
<code>def max_lists(*lst): return max(max(*lst, key=lambda v: max(v)))max_lists([1, 2, 3], [6, 7, 8], [4, 5]) # 8/<code>
12 求多個列表的最小值
<code>def min_lists(*lst): return min(min(*lst, key=lambda v: max(v)))min_lists([1, 2, 3], [6, 7, 8], [4, 5]) # 1/<code>
13 檢查list是否有重複元素
<code>def has_duplicates(lst): return len(lst) == len(set(lst))
x = [1, 1, 2, 2, 3, 2, 3, 4, 5, 6]y = [1, 2, 3, 4, 5]has_duplicates(x)
# Falsehas_duplicates(y)
# True/<code>
14 求列表中所有重複元素
<code>from collections import Counterdef find_all_duplicates(lst):
c = Counter(lst) return list(filter(lambda k: c[k] > 1, c))find_all_duplicates([1, 2, 2, 3, 3, 3])
# [2,3]/<code>
15 列表反轉
<code>def reverse(lst): return lst[::-1]reverse([1, -2, 3, 4, 1, 2])
# [2, 1, 4, 3, -2, 1]/<code>
16 浮點數等差數列
<code>def rang(start, stop, n): start,
stop,n = float('%.2f' % start), float('%.2f' % stop)
,int('%.d' % n) step = (stop-start)/n lst = [start] while n > 0:
start,n = start+step,n-1
lst.append(round((start), 2))
return lstrang(1, 8, 10)
# [1.0, 1.7, 2.4, 3.1, 3.8, 4.5, 5.2, 5.9, 6.6, 7.3, 8.0]/<code>
四、字典
1 字典值最大的鍵值對列表
<code>def max_pairs(dic): if len(dic) == 0: return dic
max_val = max(map(lambda v: v[1], dic.items()))
return [item for item in dic.items() if item[1] ==
max_val]max_pairs({'a': -10, 'b': 5, 'c': 3, 'd': 5})
# [('b', 5), ('d', 5)]/<code>
2 字典值最小的鍵值對列表
<code>def min_pairs(dic): if len(dic) == 0:
return [] min_val = min(map(lambda v: v[1], dic.items()))
return [item for item in dic.items() if item[1] == min_val]min_pairs({})
# []r = min_pairs({'a': -10, 'b': 5, 'c': 3, 'd': 5})print(r)
# [('b', 5), ('d', 5)]/<code>
3 合併兩個字典
<code>def merge_dict2(dic1, dic2): return {**dic1, **dic2}
# python3.5後支持的一行代碼實現合併字典merge_dict({'a': 1, 'b': 2}, {'c': 3})
# {'a': 1, 'b': 2, 'c': 3}/<code>
4 求字典前n個最大值
<code>from heapq import nlargest# 返回字典d前n個最大值對應的鍵def topn_dict(d, n):
return nlargest(n, d, key=lambda k: d[k])topn_dict({'a': 10, 'b': 8, 'c': 9, 'd': 10}, 3)
# ['a', 'd', 'c']/<code>
5 求最小鍵值對
<code>d={'a':-10,'b':5, 'c':3,'d':5}min(d.items(),key=lambda x:x[1])
#('a', -10)/<code>
五、集合
1 互為變位詞
from collections import Counter# 檢查兩個字符串是否 相同字母異序詞,簡稱:互為變位詞
<code>def anagram(str1, str2):
return Counter(str1) == Counter(str2)anagram('eleven+two', 'twelve+one')
# True 這是一對神器的變位詞anagram('eleven', 'twelve')
# False/<code>
六、文件操作
1 查找指定文件格式文件
<code>
import osdef find_file(work_dir,extension='jpg'):
lst = [] for filename in os.listdir(work_dir):
print(filename) splits = os.path.splitext(filename) ext = splits[1]
# 拿到擴展名 if ext == '.'+extension: lst.append(filename)
return lstfind_file('.','md')
# 返回所有目錄下的md文件/<code>
七、正則和爬蟲
1 爬取天氣數據並解析溫度值
<code>#input'with requests.get(url) as res: content = res.contenthtml = etree.HTML(content)/<code>
通過lxml模塊提取值,lxml比beautifulsoup解析在某些場合更高效
location = html.xpath('//*[@id="around"]
//a[@target="_blank"]/span/text()')
temperature = html.xpath(
'//*[@id="around"]/div/ul/li/a/i/text()')
結果:
['香河', '涿州', '唐山', '滄州', '天津', '廊坊', '太原', '石家莊', '涿鹿', '張家口', '保定', '三河', '北京孔廟', '北京國子監', '中國地質博物館', '月壇公園', '明城牆遺址公園', '北京市規劃展覽館', '什剎海', '南鑼鼓巷', '天壇公園', '北海公園', '景山公園', '北京海洋館']['11/-5°C', '14/-5°C', '12/-6°C', '12/-5°C', '11/-1°C', '11/-5°C', '8/-7°C', '13/-2°C', '8/-6°C', '5/-9°C', '14/-6°C', '11/-4°C', '13/-3°C', '13/-3°C', '12/-3°C', '12/-3°C', '13/-3°C', '12/-2°C', '12/-3°C', '13/-3°C', '12/-2°C', '12/-2°C', '12/-2°C', '12/-3°C']
<code>df = pd.DataFrame({'location':location, 'temperature':temperature})
print('溫度列')print(df['temperature'])/<code>
正則解析溫度值:
<code>df['high'] = df['temperature'].apply(lambda x: int(re.match('(-?[0-9]*?)/-?[0-9]*?°C', x).
group(1) ) )df['low'] = df['temperature'].apply(lambda x: int(re.match('-?[0-9]*?/(-?[0-9]*?)°C', x).
group(1) ) )print(df)/<code>
詳細說明子字符創捕獲
除了簡單地判斷是否匹配之外,正則表達式還有提取子串的強大功能。
用 () 表示的就是要提取的分組(group)。
比如: ^(\\d{3})-(\\d{3,8})$ 分別定義了兩個組,可以直接從匹配的字符串中提取出區號和本地號碼
<code>m = re.match(r'^(\\d{3})-(\\d{3,8})$', '010-12345')
print(m.group(0))print(m.group(1))print(m.group(2))
# 010-12345# 010# 12345/<code>
如果正則表達式中定義了組,就可以在 Match 對象上用 group() 方法提取出子串來。
注意到 group(0) 永遠是原始字符串, group(1) 、 group(2) ……表示第1、2、……個子串。
最終結果:
<code>Name: temperature, dtype: object location temperature high low0 /<code>
香河 11/-5°C 11 -51
涿州 14/-5°C 14 -52
唐山 12/-6°C 12 -63
滄州 12/-5°C 12 -54
天津 11/-1°C 11 -15
廊坊 11/-5°C 11 -56
太原 8/-7°C 8 -77
石家莊 13/-2°C 13 -28
涿鹿 8/-6°C 8 -69
張家口 5/-9°C 5 -910
保定 14/-6°C 14 -611
三河 11/-4°C 11 -412
北京孔廟 13/-3°C 13 -313
北京國子監 13/-3°C 13 -314
中國地質博物館 12/-3°C 12 -315
月壇公園 12/-3°C 12 -316
明城牆遺址公園 13/-3°C 13 -317
北京市規劃展覽館 12/-2°C 12 -218
什剎海 12/-3°C 12 -319
南鑼鼓巷 13/-3°C 13 -320
天壇公園 12/-2°C 12 -221
北海公園 12/-2°C 12 -222
景山公園 12/-2°C 12 -223
北京海洋館 12/-3°C 12 -3
2 批量轉化駝峰格式
<code>import redef camel(s): s = re.sub(r"(\\s|_|-)+", " ", s)
.title().replace(" ", "") return s[0].lower() + s[1:]
# 批量轉化def batch_camel(slist): return [camel(s) for s in slist]batch_camel(['student_id', '
student\\tname', 'student-add']) #['studentId', 'studentName', 'studentAdd']/<code>
八、繪圖
1 turtle繪製奧運五環圖
結果:
2 turtle繪製漫天雪花
結果:
3 4種不同顏色的色塊,它們的顏色真的不同嗎?
4 詞頻雲圖
<code>import hashlibimport pandas as pdfrom wordcloud import
WordCloudgeo_data=pd.read_excel(r"../data/geo_data.xlsx")words = ','.
join(x for x in geo_data['city'] if x != [])
#篩選出非空列表值wc = WordCloud( background_color="green",
#背景顏色"green"綠色 max_words=100, #顯示最大詞數
font_path='./fonts/simhei.ttf', #顯示中文 min_font_size=5,
max_font_size=100, width=500
#圖幅寬度 )x = wc.generate(words)x.to_file('../data/geo_data.png') /<code>
八、生成器
1 求斐波那契數列前n項(生成器版)
<code>def fibonacci(n): a, b = 1, 1 for _ in range(n):yield a a,
b = b, a + blist(fibonacci(5)) # [1, 1, 2, 3, 5]/<code>
2 將list等分為子組(生成器版)
<code>from math import ceildef divide_iter(lst, n):
if n <= 0: yield lst return i, div = 0, ceil(len(lst) / n) while i < n:
yield lst[i * div: (i + 1) * div] i += 1list(divide_iter([1, 2, 3, 4, 5], 0))
# [[1, 2, 3, 4, 5]]list(divide_iter([1, 2, 3, 4, 5], 2))
# [[1, 2, 3], [4, 5]]/<code>
九、keras
1 Keras入門例子
<code>import numpy as npfrom keras.modelsimport Sequentialfrom keras.
layers import Densedata = np.random.random((1000, 1000))
labels = np.random.randint(2, size=(1000, 1))
model = Sequential()model.add(Dense(32, activation='relu',
input_dim=100))model.add(Dense(1, activation='sigmoid'))
model.compile(optimize='rmsprop', loss='binary_crossentropy',
metrics=['accuracy'])model.fit(data, labels, epochs=10,
batch_size=32)predictions = model.predict(data)/<code>
最後小編幫助大家整理了一套python教程,下面展示了部分,希望也能幫助對編程感興趣,想做數據分析,人工智能、爬蟲或者希望從事編程開發的小夥伴,畢竟python工資也還可以,如果能幫到你請點贊、點贊、點贊。
以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作具有一定的參考學習價值.
如果你喜歡python,並覺得這篇文章對你有益的話,麻煩多多點贊關注支持!!!!
閱讀更多 程序猿老旭 的文章