我爱编程程序员Python小推车

Python的容器数据类型

2018-12-03  本文已影响20人  zhyuzh3d

Sequence序列对象

lists列表, 元组tuples, and range

通用序列操作:

list列表

>>> sorted((3,2,1))
[1, 2, 3]
>>> list((1,2,3))
[1, 2, 3]
>>> li=[{'a':22},{'a':12},{'a':100}]
>>> sorted(li,key=lambda x:x['a'])
[{'a': 12}, {'a': 22}, {'a': 100}]

Tuples元组

range

>>> list(range(0, -10, -1))
[0, -1, -2, -3, -4, -5, -6, -7, -8, -9]
>>> list(range(0))
[]
>>> list(range(1, 0))
[]
>>> range(0, 3, 2) == range(0, 4, 2)
True

range存在.start,.stop,.step属性

集合类型set

>>> a={1,2,3,4}
>>> b={3,4,5,6}
>>> a.isdisjoint(b)
False
>>> c={5,6}
>>> a.isdisjoint(c)
True

字典dict

>>> a = dict(one=1, two=2, three=3)
>>> b = {'one': 1, 'two': 2, 'three': 3}
>>> c = dict(zip(['one', 'two', 'three'], [1, 2, 3]))
>>> d = dict([('two', 2), ('one', 1), ('three', 3)])
>>> e = dict({'three': 3, 'one': 1, 'two': 2})
>>> a == b == c == d == e
True
>>> dishes = {'eggs': 2, 'sausage': 1, 'bacon': 1, 'spam': 500}
>>> keys = dishes.keys()
>>> values = dishes.values()

>>> # iteration
>>> n = 0
>>> for val in values:
...     n += val
>>> print(n)
504

>>> # keys and values are iterated over in the same order (insertion order)
>>> list(keys)
['eggs', 'sausage', 'bacon', 'spam']
>>> list(values)
[2, 1, 1, 500]

>>> # view objects are dynamic and reflect dict changes
>>> del dishes['eggs']
>>> del dishes['sausage']
>>> list(keys)
['bacon', 'spam']

>>> # set operations
>>> keys & {'eggs', 'bacon', 'salad'}
{'bacon'}
>>> keys ^ {'sausage', 'juice'}
{'juice', 'sausage', 'bacon', 'spam'}
上一篇 下一篇

猜你喜欢

热点阅读