Python高级编程-13优化:解决方案
来源:互联网 发布:matlab复制一个矩阵 编辑:程序博客网 时间:2024/04/30 08:43
在一个有序list中进行二分查找
find.py
from bisect import bisectdef find(seq, el): pos = bisect(seq, el) if pos == 0 or (pos == len(seq) and seq[-1] != el): return -1 return pos - 1seq = [2, 3, 7, 8, 9]find(seq, 9) # 4find(seq, 10) # -1find(seq, 0) # -1find(seq, 7) # 2
使用set保存无重复key的list
my_set.py
seq = ['a', 'a', 'b', 'c', 'c', 'd']res = set(seq)print res # set(['a', 'c', 'b', 'd'])
deque
my_deque.py
from collections import dequed = deque()d.append('1')d.append('2')d.append('3')print d # deque(['1', '2', '3'])print len(d) # 3print d[0] # 1print d[-1] # 3d.pop()d.popleft()print d # deque(['2'])d.extendleft(['1', '0'])d.extend(['3', '4', '5'])print d # deque(['0', '1', '2', '3', '4', '5'])
defaultdict
my_defaultdict.py
from collections import defaultdictclass Person(object): def __init__(self, name, age): self.name = name self.age = age def __str__(self): return self.name def __repr__(self): return self.namepersons = [Person('bob', 20), Person('jack', 20), Person('mary', 22)]persons_by_age = defaultdict(list)for person in persons: persons_by_age[person.age].append(person)for k, v in persons_by_age.items(): print ':'.join([str(k), str(v)])# 20:[bob, jack]# 22:[mary]
namedtuple
my_namedtuple.py
Bob = ('bob', 30, 'male')print 'Representation:', Bob # Representation: ('bob', 30, 'male')Jane = ('Jane', 29, 'female')print 'Field by index:', Jane[0] # Field by index: Janefor people in [Bob, Jane]: print "%s is %d years old %s" % people# bob is 30 years old male# Jane is 29 years old femalefrom collections import namedtuplePerson = namedtuple('Person', 'name age gender')print 'Type of Person:', type(Person) # Type of Person: <type 'type'>Bob = Person(name='Bob', age=30, gender='male')print 'Representation:', Bob # Representation: Person(name='Bob', age=30, gender='male')Jane = Person(name='Jane', age=29, gender='female')print 'Field by Name:', Jane.name # Field by Name: Janefor people in [Bob, Jane]: print "%s is %d years old %s" % people# Bob is 30 years old male# Jane is 29 years old female
0 0
- Python高级编程-13优化:解决方案
- 《Python高级编程》读书笔记
- python 高级编程 一
- python 高级编程 二
- python 高级编程 三
- python 高级编程 四
- Python高级编程技巧
- Python高级编程技巧
- Python高级编程技巧
- Python高级编程技巧
- Python高级编程技巧
- Python高级编程技巧
- Python高级编程技巧
- Python高级编程技巧
- Python高级编程技巧
- Python 高级编程技巧
- python高级编程
- Python高级编程技巧
- 《javascript设计模式与开发实践》阅读笔记(12)—— 享元模式
- resultMap和resultType引起的错误
- .net中input和button点击刷新问题
- 一个java面试官的感慨来源于网络
- 数组的二分查找法查找元素以及查处删除元素
- Python高级编程-13优化:解决方案
- react-native遇到依赖module问题
- MxNet系列——how_to——multi_devices
- 关于js跨域JSONP的使用
- OpenCV documentation 官方文档
- HTTP状态码
- Android模板设计模式之 - 构建整个应用的BaseActivity
- spring(4)---加载spring容器的3种方式
- Jetson TX1 硬件配置概览