python--数据结构和算法
2015-12-22 15:59
411 查看
1.将序列分解为单独的变量
任何序列(或者可迭代的对象)都可以通过简单的赋值操作来分解为单独的变量,唯一的要求是变量的总数和结构要与序列向吻合例如
>>> p=(4,5) >>> x,y=p >>> x 4 >>> y 5
<span style="font-size:18px;">data=['acme',50,90.1,(2012,12,21)] name,shares,prices,date=data print(name) print(date) </span>
<span style="font-size:18px;">acme (2012, 12, 21) </span>
2从任意长度的可迭代对象中分解元素
Python的表达式“*表达式”可用来解决这个问题
>>> line = ‘nobody:*:-2:user:/home‘ >>> uname, *others, path = line.split(‘:‘) >>> uname ‘nobody‘ >>> path ‘/home‘
对于分解位置或者任意长度的可迭代对象,这样再合适不过了。对于固定的组件或者模式(如,元素2以后的都是电话号码,但是电话号码的数量未知),使用星号表达式可以方便快捷的分解。
3保存最后N个元素
from collections import deque q=deque(maxlen=3) q.append(1) q.append(2) q.append(3) print(q)
>>>deque([1, 2, 3], maxlen=3)
q.append(4)
<pre class="python" name="code">>>>deque([2, 3, 4], maxlen=3)
q.appendleft(5)
>>>deque([5, 2, 3], maxlen=3)
q.pop() >>>deque([5, 2], maxlen=3)
q.popleft()
>>>deque([2], maxlen=3)
4找到集合中最大最小的N个元素
heapq模块中有两个函数nlargest()nsmallest()
这两个函数可以接受一个参数key 从而允许它们工作在更加复杂的数据结构之上
import heapq nums=[1,2,3,4,5,5,6] print(heapq.nlargest(3,nums))#print[6,5,5] print(heapq.nsmallest(3,nums))#prints[1,2,3]
portfolio=[{'name':'aaple','price':50,'shares':89.09}, {'name':'baple','price':150,'shares':819.09}, {'name':'aple','price':30,'shares':9.09}]cheap=heapq.nsmallest(1,portfolio,key=lambda s:s['price'])expensive=heapq.nlargest(1,portfolio,key=lambda s:s['price'])print(cheap)print(expensive)
5
相关文章推荐
- Python动态类型的学习---引用的理解
- Python3写爬虫(四)多线程实现数据爬取
- 垃圾邮件过滤器 python简单实现
- 下载并遍历 names.txt 文件,输出长度最长的回文人名。
- install and upgrade scrapy
- Scrapy的架构介绍
- Centos6 编译安装Python
- 使用Python生成Excel格式的图片
- 让Python文件也可以当bat文件运行
- [Python]推算数独
- Python中zip()函数用法举例
- Python中map()函数浅析
- Python将excel导入到mysql中
- Python在CAM软件Genesis2000中的应用
- 使用Shiboken为C++和Qt库创建Python绑定
- FREEBASIC 编译可被python调用的dll函数示例
- Python 七步捉虫法