集合类操作

筛选操作

>>> l = [1, 2, 3]
>>> filter(lambda i:i%2 == 1, l)
[1, 3]

映射操作

>>> l = [1, 2, 3]
>>> map(lambda i:i*2, l)
[2, 4, 6]

归约操作

>>> l = [1, 2, 3]
>>> reduce(lambda x,y:x+y, l)
6

collections模块

命名元组

>>> from collections import namedtuple
>>> Point = namedtuple('Point', ['x', 'y'])
>>> p = Point(1, 2)
>>> p.x
1
>>> p.y
2

>>> for p in [(1, 2), (3, 4), (5, 6)]:
...   p = Point._make(p)
...   p
...
Point(x=1, y=2)
Point(x=3, y=4)
Point(x=5, y=6)

双端队列

>>> from collections import deque
>>> de = deque()

>>> de.append(2)
>>> de
deque([2])
>>> de.appendleft(1)
>>> de
deque([1, 2])
>>> de.append(3)
>>> de
deque([1, 2, 3])

>>> de.pop()
3
>>> de
deque([1, 2])
>>> de.popleft()
1
>>> de
deque([2])
>>> de.pop()
2
>>> de
deque([])

默认字典

>>> from collections import defaultdict
>>> d = defaultdict(lambda : 'N/A')
>>> d[1]
'N/A'
>>> d[1] = 1
>>> d[1]
1

顺序字典

字典方式构建

>>> d = {'a':1, 'b':2, 'c':3}
>>> d
{'a': 1, 'c': 3, 'b': 2}

>>> from collections import OrderedDict
>>> d = OrderedDict({'a': 1, 'c': 3, 'b': 2})
>>> d
OrderedDict([('a', 1), ('c', 3), ('b', 2)])

字典方式构建依然不能保证顺序

元组方式构建

>>> d = dict([('a', 1), ('b', 2), ('c', 3)])
>>> d
{'a': 1, 'c': 3, 'b': 2}

>>> from collections import OrderedDict
>>> d = OrderedDict([('a', 1), ('b', 2), ('c', 3)])
>>> d
OrderedDict([('a', 1), ('b', 2), ('c', 3)])

元组方式构建依然能够保证顺序

计数器

>>> from collections import Counter
>>> c = Counter()
>>> for i in 'hello world':
...   c[i] = c[i] + 1
...
>>> c
Counter({'l': 3, 'o': 2, ' ': 1, 'e': 1, 'd': 1, 'h': 1, 'r': 1, 'w': 1})

string模块

str原生方法

>>> s = 'hello world'

>>> s.count('l')
3

>>> s.ljust(17)
'hello world      '
>>> s.rjust(17)
'      hello world'
>>> s.center(17)
'   hello world   '

>>> s.upper()
'HELLO WORLD'
>>> s.upper().lower()
'hello world'
>>> s.title()
'Hello World'
>>> s.capitalize()
'Hello world'
>>> s.capitalize().swapcase()
'hELLO WORLD'

string模块方法

>>> s = 'hello world'

>>> import string

>>> string.count(s, 'l');
3

>>> string.ljust(s, 17)
'hello world      '
>>> string.rjust(s, 17)
'      hello world'
>>> string.center(s, 17)
'   hello world   '

>>> string.upper(s)
'HELLO WORLD'
>>> string.lower(string.upper(s))
'hello world'
>>> string.capitalize(s)
'Hello world'
>>> string.swapcase(string.capitalize(s))
'hELLO WORLD'

string列表

>>> import string
>>> string.lowercase
'abcdefghijklmnopqrstuvwxyz'
>>> string.uppercase
'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
>>> string.letters
'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
>>> string.digits
'0123456789'
>>> string.hexdigits
'0123456789abcdefABCDEF'
>>> string.octdigits
'01234567'
>>> string.punctuation
'!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'
>>> string.whitespace
'\t\n\x0b\x0c\r '
>>> string.printable
'0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~ \t\n\r\x0b\x0c'
Copyright © zhujipeng 2017 all right reserved,powered by Gitbook 该文件修订时间: 2017-12-16 15:12:10

results matching ""

    No results matching ""