Python高階技巧(一)

2021-08-07 06:09:13 字數 4944 閱讀 3433

命名統計 collections

提取公共鍵 map reduce

佇列pickle

filter(lambda x: x>0 , list)

[ x for x in data if x >= 0]

from random import randint

data = [ randint(-10,10) for _ in range(10)]

res = filter(lambda x : x>=0 , data)

aa = [ x for x in

data if x >= 0]

from random import randint

d =

res =

print(res)

data = [-5, -7, -6, 7, 4, -3, -8, -9, 7, 0]

se = set(data)

res =

aa = filter(lambda x:x%3==0 , se)

# 測一下時間消耗

# (進入 ipython)

data = [-5, -7, -6, 7, 4, -3, -8, -9, 7, 0]

timeit filter(lambda x : x>=0 , data)

timeit [ x for x in

data if x >= 0]

# 元組查詢極快,元素不可修改。

name,age,***,email = range(4)

student = ('jim',16,'male','[email protected]')

print(student[email])

from collections import namedtuple

student = namedtuple('student',['name','age','***','email'])

s=student('jim',16,'male','[email protected]')

print(s.name)

data = [6, 1, 8, 1, 8, 2, 8, 4, 8, 6, 3, 4, 6, 3, 4, 5, 2, 9, 8, 3]

c = dict.fromkeys(data,0)

for x in

data:

c[x]+=1

print(c)

# 加強版

from collections import counter

data = [6, 1, 8, 1, 8, 2, 8, 4, 8, 6, 3, 4, 6, 3, 4, 5, 2, 9, 8, 3]

c2 = counter(data)

print(c2)

print(c2[1],c2[8])

# most_common 找出出現頻率最高的三個元素

print(c2.most_common(3))

import re

from collections import counter

with

open('secret.txt') as f:

text = f.read()

textlist = re.split('\w+',text)

print(len(textlist))

c3 = counter(re.split('\w+',text))

# print(c3)

print(c3.most_common(6))

from

random import randint,sample

from functools import reduce

left = 2

right = 6

s1 =

s2 =

s3 =

# 1.4 µs ± 55.8 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

print(s1.keys() & s2.keys() & s3.keys())

# 2.14 µs ± 36.3 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

reduce(lambda a,b:a&b , map(dict.keys,[s1,s2,s3]))

from random import randint,sample

aa = sample('abcdefg',randint(1,5))

print(aa)

from

random import randint,sample

left = 2

right = 6

s1 =

s2 =

s3 =

m = map(dict.keys,[s1,s2,s3])

print(list(m))

from functools import reduce

deff

(x, y):

return x + y

# reduce第乙個引數是 函式 , 第二個引數是 列表、集合、元組或者map 之類可迭代的物件

reduce(f,[1,3,5,7,9],100) #第三個引數不要也行,意義是 設定初始值

deque佇列 以及 pickle持續化儲存物件(不用放在記憶體裡面)

from random import randint

from collections import deque

import pickle

history = deque(maxlen=5)

n=randint(0,100)

defguess

(k):

if k == n:

print('*****(`_`)*****')

return

true

elif k > n:

print("too big")

else:

print('too small')

while

true:

line = input("guess it ! :")

if line.isdigit():

k = int(line)

guess(k)

with open('history.txt','wb') as f:

pickle.dump(history,f)

elif line == "h":

with open('history.txt','rb') as f:

his = pickle.load(f)

print(his)

import pickle

from

random import randint

alist = [randint(0,100) for _ in range(10)]

with

open('testnote','wb') as f:

pickle.dump(alist,f)

with

open('testnote','rb') as f:

alist = pickle.load(f)

print(alist)

json 和 pickle 都是儲存到硬碟上 持久儲存

json被各種語言支援 , pickle只用來python程式之間使用。

json在python裡面只支援列表字典, pickle支援python的所有資料型別。

import pickle

from random import randint

import json

aa = [randint(0,100) for _ in range(10)]

atuple = tuple(aa)

aset = set(aa)

adic =

defppickle

(obj):

filename = 'picklenote'

with open(filename,'wb') as f:

pickle.dump(obj,f)

with open(filename,'rb') as f:

res = pickle.load(f)

print(res)

defjjson

(obj):

filename = 'jsonnote'

with open(filename,'w') as f:

json.dump(obj,f)

with open(filename,'r') as f:

res = json.load(f)

print(res)

print("\n+pickle:")

ppickle(aa)

ppickle(atuple)

ppickle(adic)

ppickle(aset)

print("\n+json:")

jjson(aa)

jjson(atuple)

jjson(adic)

# jjson(aset) # typeerror: object of type 'set' is not json serializable

Python高階(一) python技巧

除了常見的列表建立方法外,還有一下幾種建立方式 split 函式用來分割文字,可以給定分割符號,如上以 為分割符 suits spade,heart,club,diamond split 用for.in 語句塊可以使得列表的建立更加簡潔,尤其是需要新增大量元素。list seq 函式用來建立,不過只...

python骨灰技巧 Python 高階技巧

一 生成器 通過列表生成式,我們可以直接建立乙個列表。但是,受到記憶體限制,列表容量肯定是有限的。而且,建立乙個包含100萬個元素的列表,不僅占用很大的儲存空間,如果我們僅僅需要訪問前面幾個元素,那後面絕大多數元素占用的空間都白白浪費了。這個其實是惰性求值,資料不是全部一下子載入到記憶體中,而是乙個...

python高階程式設計技巧

個人部落格點這裡 方法1 通過迭代來進行判斷篩選 解決方案 函式式程式設計 解決方案 使用collections.counter物件 將序列傳入counter的構造器,得到counter物件是元素頻度的字典 counter.most common n 方法得到頻度最高的n個元素的列表 解決方案 使用...