python--数据结构和算法

来源:互联网 发布:office of mac免费版本 编辑:程序博客网 时间:2024/05/21 08:35

1.将序列分解为单独的变量

任何序列(或者可迭代的对象)都可以通过简单的赋值操作来分解为单独的变量,唯一的要求是变量的总数和结构要与序列向吻合

例如

>>> p=(4,5)>>> x,y=p>>> x4>>> y5
<span style="font-size:18px;">data=['acme',50,90.1,(2012,12,21)]name,shares,prices,date=dataprint(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 dequeq=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 heapqnums=[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

0 0
原创粉丝点击