cookbook_數據結構和算法

1.1將數據分解為單獨的變量
list_a = [1,2,3,4,5,6,7,8,9]
a,b,c,d,e,f,g,h,i = list_a
print(a,b,c,d,e,f,g,h,i)
#使用相等數量的參數來接收
_,b,c,d,e,f,g,h,_ = list_a 
print(b,c,d,e,f,g,h)
#不要的數據使用一個沒有用的變量接收
View Code

?

1.2從任意長度的可迭代對象中分解元素

使用 * XXX實現

list_a = range(20)
first,*middle,last = list_a
print(first,middle,last)
#使用*來接收任意數量,甚至沒有,返回一個list#當一個元祖內有一個標志位時,一個較好的應用
records = [("foo",1,2),("bar","hello"),("foo",3,4)
]def do_foo(x,y):print("foo",x,y)def do_bar(s):print("bar",s)for tags,*args in records:if tags == "foo":do_foo(*args)elif tags == "bar":do_bar(*args)
View Code

?

1.3保存最后N個元素

collections.deque()

import collections#使用collections.deque(maxlen=5)來定義一個固定長度的list,有新數據寫入時如果已經達到maxlen,會自動刪除最早插入的數據
def search(lines,pattern,history = 5):previous_lines = collections.deque(maxlen=history)for line in lines:if pattern in line:yield line,previous_linesprevious_lines.append(line)if __name__ =="__main__":with open("test.txt","r",encoding="utf8") as f:for line,previous in search(f,"python",5):for pline in previous:print(pline,end="")print(line,end="")print("-"*20)#collections.deque使用簡介
#一個更加強大的list

queue = collections.deque(["jiao","li",'hao',"yu"])
queue.appendleft("wu")
print(queue)
queue.append("haha")
print(queue)
queue.popleft()
print(queue)
print(queue[4])
View Code
 
1.4找到最大或最小的N個元素

heapq.nlargest(),heapq.nsmallest()

import heapqnums = [5,56,7,6,34,2,5,7,6,89,80,-90,0,9,-67,5,45,]print(min(nums))
print(max(nums))print(heapq.nlargest(3,nums))
print(heapq.nsmallest(3,nums))#可支持更加復雜的數據結構

portfolio = [{"name":"jiao","age":24},{"name":"jsdfo","age":2},{"name":"jisd","age":12},{"name":"jdo","age":36},{"name":"li","age":25},{"name":"jgd","age":50},
]print(heapq.nlargest(3,portfolio,key=lambda s:s['age']))
print(max(portfolio,key=lambda s:s['age']))
View Code

?

?

1.5實現優先級隊列

heapq.heappush(),heapq.heappop()

import heapq#列表中實際存一個元組,(-priority,self._index,item)
class PriorityQueue:def __init__(self):self._queue = []self._index = 0def push(self,item,priority):heapq.heappush(self._queue,(-priority,self._index,item))self._index += 1def pop(self):return heapq.heappop(self._queue)[-1]def get(self):return self._queueq = PriorityQueue()
q.push("foo",2)
q.push("sdf",3)
q.push("sfasc",5)
q.push("fdsg",4)
print(q.pop())
print(q.get())
View Code
?
1.6在字典中將鍵映射到多個值上

collections.defaultdict(list),collections.defaultdict(set)

import collectionsd = collections.defaultdict(list)#自動初始化,不用判斷是否存在
d["a"].append(1)
d["a"].append(1)
d["a"].append(1)
d["a"].append(1)
print(d['a'])
View Code

?

1.7讓字典保持有序

collections.OrderedDict()

import collectionsd = collections.OrderedDict()#普通字典的兩倍,大數據不應該使用
d['foo'] = 1
d["bar"] = 2
d["spam"] = 3
d["gork"] = 4
for i in d:print(i)
View Code

?

1.8與字典有關的計算問題

zip(),min(),sorted().max()

#字典進行大小運算時都是使用key值進行大小比較,而我們一般想要用value值比較,而且還想要得到該值的key

prices = {"ACME":23,"AAPL":345,"IBM":34,"FB":24
}#利用zip,zip返回一個迭代器,只能使用一次

min_price = min(zip(prices.values(),prices.keys()))
print(min_price)#排序
price_sorted = sorted(zip(prices.values(),prices.keys()))
print(price_sorted)
View Code

?

?
1.9在兩個字典中尋找相同點

?

a = {"x":2,"y":5,"z":7
}b = {"x":2,"y":8,"w":4
}print(a.keys() & b.keys())#尋找相同的key
print(a.keys() - b.keys())#尋找a中有b中沒有的key
print(a.items() & b.items())#尋找相同項
View Code

?

?

1.10從序列中移除重復項且保持元素間順序不變
def dedupe(items,key = None):seen = set()for item in items:val = item if key is None else key(item)if val not in seen:yield itemseen.add(val)
View Code

?

?

?

?

?

?

轉載于:https://www.cnblogs.com/jiaojianglong/p/11260093.html

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/247339.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/247339.shtml
英文地址,請注明出處:http://en.pswp.cn/news/247339.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

Angular自學筆記(二)顯示數據 綁定屬性

顯示數據 1.顯示數據 ng的模版中,默認用雙大括號{{}}綁定組件中的變量顯示出來 import {Component } from @angular/core; @Component({selector: app-root,template: `<h1>{{title}}</h1><h2>My favorite hero is: {{myHero}}</h2>`

機器學習概覽

什么是機器學習&#xff1f; 廣義概念&#xff1a; 機器學習是讓計算機具有學習的能力&#xff0c;無需明確的編程 —— 亞瑟薩繆爾&#xff0c;1959 工程概念&#xff1a; 計算機程序利用經驗 E 學習任務 T&#xff0c;性能是 P&#xff0c;如果針對任務 T 的性能 P 隨著經驗 …

Angular自學筆記(?)TemplateRef和ViewContainerRef

ElementRef 由于ng是跨平臺的為了減少視圖層和渲染層的耦合也為了讓ng更適應多平臺,ng幫我們封裝了ElementRef,我們可以通過ElementRef拿到native元素(在瀏覽器中也就是我們常說的DOM元素) 下面我們看一段代碼 import {Component, ElementRef, AfterViewInit } from @angu…

python之re模塊

re模塊 re&#xff08;正則&#xff09;簡介 ? 正則就是用一些具有特殊含義的符號組合到一起&#xff08;稱為正則表達式&#xff09;來描述字符或者字符串的方法。或者說&#xff1a;正則就是用來描述一類事物的規則。 re元字符 元字符匹配內容\w匹配字母&#xff08;包含中文…

Angular自學筆記(?)ViewChild和ViewChildren

ViewChild 最好在ngAfterViewInit之后,獲取模版上的內容 獲取普通dom import {AfterViewInit, Component, ElementRef, OnInit, ViewChild} from @angular/core;@Component({selector: app-view-child

IPropertySet接口

Members AllProperties MethodsDescriptionCountThe number of properties contained in the property set.包含屬性個數GetAllPropertiesThe name and value of all the properties in the property set.GetPropertiesThe values of the specified properties.GetPropertyThe …

Angular自學筆記(?)ContentChild和ContentChildren

ContentChild 用法類似ViewChild, 獲取投影中到組件或指令還有元素dom等 獲取投影中但組件 import {AfterViewInit, Component, ElementRef, OnInit, ViewChild} from @angular/core;@Component({selector: app-content-child-panel,templateUrl

Angular自學筆記(?)屬性型指令

基本概念 用于改變DOM元素的外觀或行為的指令 組件是一種特殊的指令 import {Component} from @angular/core; @Component({selector: app-root,template: `<!--<app-for></app-for>--><div app-for>dasfsada</div>`,

SNS編年史

準備起草。轉載于:https://www.cnblogs.com/cmleung/archive/2009/11/26/1611546.html

Angular自學筆記(?)結構型指令

內置指令的展開寫法 ngIf import {Component } from @angular/core; @Component({selector: app-root,template: `<button (click)="show = !show">toggle</button><p *ngIf="show as aa">一段文字 {{ aa }}</p><ng-template…

SQL on and 和 on where 的區別

on and 和 on where 的 區別 在使用 left join 時, on and 和 on where 會有區別&#xff1b;1. on的條件是在連接生成臨時表時使用的條件,以左表為基準 ,不管on中的條件真否,都會返回左表中的記錄  on 后面 and 都是對右表進行篩選 2.where是全部連接完后&#xff0c;對臨時…

:host :host-context ::ng-deep詳解

:host 與 ::ng-deep :host 表示選擇當前的組件。 ::ng-deep 可以忽略中間className的嵌套層級關系。直接找到你要修改的className。 在使用一些第三方的組件的時候&#xff0c;要修改組件的樣式。 這種情況下使用: :host ::ng-deep .className{新的樣式...... } :host {backg…

Java生鮮電商平臺-緩存架構實戰

Java生鮮電商平臺-緩存架構實戰 說明&#xff1a;在Java生鮮電商中&#xff0c;緩存起到了非常重要的作用&#xff0c;目前整個項目中才用的是redis做分布式緩存. 緩存集群 緩存集群存在的問題 1.熱key 緩存集群中的某個key瞬間被數萬甚至十萬的并發請求打爆。 2.大value 某個k…

Java生鮮電商平臺-深入理解微服務SpringCloud各個組件的關聯與架構

Java生鮮電商平臺-深入理解微服務SpringCloud各個組件的關聯與架構 概述 毫無疑問&#xff0c;Spring Cloud是目前微服務架構領域的翹楚&#xff0c;無數的書籍博客都在講解這個技術。不過大多數講解還停留在對Spring Cloud功能使用的層面&#xff0c;其底層的很多原理&#xf…

Angular自學筆記(?)DI提供者

類提供者 類提供者的創建和使用 假設有logger類: import {Injectable } from @angular/core;@Injectable() export class LoggerService {logs: string[] = [

Angular自學筆記(?)生命周期

從實例化組件,渲染組件模板時,各聲明周期就已開始 ngOnChanges 輸入屬性發生變化是觸發,但組件內部改變輸入屬性是不會觸發的 import {Component, Input, OnInit, OnChanges } from @angular/core;@Component({selector: app-life-cycle,templateUrl:

[轉載]httpClient.execute拋Connection to refused異常問題

在4.0之后android采用了嚴格模式&#xff1a;所以在你得activity創建的時候&#xff0c;在super.onCreate(savedInstanceState);后面加上這個 StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder() .detectDiskReads() .detectDiskWrites(…

Angular自學筆記(?)依賴注入

什么是依賴注入 依賴注入(DI)是一種設計模式, 也有相應的框架,比如InversifyJS Angular 有自己的 DI 框架, DI 框架會在實例化該類時向其提供這個類所聲明的依賴項 帶修飾符的參數 在ts中,一個類的參數如果帶上修飾符,那個參數就變成了類的實例屬性 class Mobile {co…

MSN8.0經常出現連接錯誤,如何解決?

連接錯誤有很多種情形&#xff0c;請您先查看下連接錯誤代碼 然后可以嘗試以下解決辦法--------- 如何解決錯誤 81000301 或 81000306 您登錄 MSN Messenger 時&#xff0c;可能會收到以下錯誤消息&#xff1a; 我們無法讓您登錄到 MSN Messenger&#xff0c;可能是因為服務或 …

@ViewChild 的三種常用方法

//--1------ 在angular中進行dom操作 <div #dom>這是一個div</div> //放置一個錨點domimport { ElementRef, ViewChild } from angular/core;ViewChild(dom,{static:true}), eleRef:ElementRef; //static-True表示在運行更改檢測之前解析查詢結果&#xff0c;false…