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.mzph.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…