重新撸 Python 官方文档02--Tuples, Sets and Dictionaries

1 Tuples and Sequences

Sequence Types — list, tuple, range

>>> t = 12345, 54321, 'hello!'
>>> t[0]
12345
>>> t
(12345, 54321, 'hello!')
>>> # Tuples may be nested:
... u = t, (1, 2, 3, 4, 5)
>>> u
((12345, 54321, 'hello!'), (1, 2, 3, 4, 5))
>>> # Tuples are immutable:
... t[0] = 88888
Traceback (most recent call last):
  File "", line 1, in 
TypeError: 'tuple' object does not support item assignment
>>> # but they can contain mutable objects:
... v = ([1, 2, 3], [3, 2, 1])
>>> v
([1, 2, 3], [3, 2, 1])

tuple用逗号区分开元素
输出时总是带括号,输入时可以不带括号,不过带括号比较好,不然用以引起误解.
tuple 和 list 很像,不过,tuple是不可变的
tuple 有零个元素还是一个元素

>>> empty = ()
>>> singleton = 'hello',    # <-- note trailing comma
>>> len(empty)
0
>>> len(singleton)
1
>>> singleton
('hello',)

构建tupple 与拆解tuple

>>>t = x, y, z
>>>x, y, z = t

2 Sets

set 是 没有重复元素的无序集合. 用花括号或者 set()来创建,但是创建空set要用set(),而不是{},{}用来创建空dictionary

简略演示

>>> basket = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana'}
>>> print(basket)                      # show that duplicates have been removed
{'orange', 'banana', 'pear', 'apple'}
>>> 'orange' in basket                 # fast membership testing
True
>>> 'crabgrass' in basket
False

>>> # Demonstrate set operations on unique letters from two words
...
>>> a = set('abracadabra')
>>> b = set('alacazam')
>>> a                                  # unique letters in a
{'a', 'r', 'b', 'c', 'd'}
>>> a - b                              # letters in a but not in b
{'r', 'd', 'b'}
>>> a | b                              # letters in a or b or both
{'a', 'c', 'r', 'd', 'b', 'm', 'z', 'l'}
>>> a & b                              # letters in both a and b
{'a', 'c'}
>>> a ^ b                              # letters in a or b but not both
{'r', 'd', 'b', 'm', 'z', 'l'}

差不多就是与或并之类的逻辑

set 也支持推导式

>>> a = {x for x in 'abracadabra' if x not in 'abc'}
>>> a
{'r', 'd'}

3 Dictionaries

dictionary就是 key: value 对
一些例子

>>> tel = {'jack': 4098, 'sape': 4139}
>>> tel['guido'] = 4127
>>> tel
{'sape': 4139, 'guido': 4127, 'jack': 4098}
>>> tel['jack']
4098
>>> del tel['sape']
>>> tel['irv'] = 4127
>>> tel
{'guido': 4127, 'irv': 4127, 'jack': 4098}
>>> list(tel.keys())
['irv', 'guido', 'jack']
>>> sorted(tel.keys())
['guido', 'irv', 'jack']
>>> 'guido' in tel
True
>>> 'jack' not in tel
False

>>> dict([('sape', 4139), ('guido', 4127), ('jack', 4098)])
{'sape': 4139, 'jack': 4098, 'guido': 4127}

另外 字典也有 推导式

>>> {x: x**2 for x in (2, 4, 6)}
{2: 4, 4: 16, 6: 36}
>>> dict(sape=4139, guido=4127, jack=4098)
{'sape': 4139, 'jack': 4098, 'guido': 4127}

4 循环技巧

循环字典时,items()可以同时获取 key 和 value

>>> knights = {'gallahad': 'the pure', 'robin': 'the brave'}
>>> for k, v in knights.items():
...     print(k, v)
...
gallahad the pure
robin the brave

循环序列时, enumerate()可以同时获得索引以及对应的值

>>> for i, v in enumerate(['tic', 'tac', 'toe']):
...     print(i, v)
...
0 tic
1 tac
2 toe

循环两个或更多的序列时,可以用zip()来讲对应元素配对.

>>> questions = ['name', 'quest', 'favorite color']
>>> answers = ['lancelot', 'the holy grail', 'blue']
>>> for q, a in zip(questions, answers):
...     print('What is your {0}?  It is {1}.'.format(q, a))
...
What is your name?  It is lancelot.
What is your quest?  It is the holy grail.
What is your favorite color?  It is blue.

逆循环时,可以用 reversed()

>>> for i in reversed(range(1, 10, 2)):
...     print(i)
...
9
7
5
3
1

用排序后的顺序进行循环,可以用 sorted()返回一个排完序的列表同时不改变原来的序列

>>> basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']
>>> for f in sorted(set(basket)):
...     print(f)
...
apple
banana
orange
pear

循环时改变一个列表总是很爽,但是更简单也更安全的是创建一个新的列表来替换.

>>> import math
>>> raw_data = [56.2, float('NaN'), 51.7, 55.3, 52.5, float('NaN'), 47.8]
>>> filtered_data = []
>>> for value in raw_data:
...     if not math.isnan(value):
...         filtered_data.append(value)
...
>>> filtered_data
[56.2, 51.7, 55.3, 52.5, 47.8]

5 更多的条件语句

while if 可以有任意运算符 而不仅仅是比较

in not in 检查一个值是否在一个序列里面.
is is not 检查两个对象是不是真的相同的对象.
以上几个运算符有相同优先级,但是比数字操作符要低一些.

逻辑运算符 andor有时会有 not 否定形式. not有最高优先级 而 or的优先级是最低的
比如
A and not B or C 等价于 (A and (not B)) or C

andor又叫短路运算符,从左向右计算,如果值一旦确定,则计算停止.比如
A``C是真的,B是假,那 A and B and C就不再去计算C的表达式

把比较式 或者布尔表达式的结果赋值也是可以的,比如:

>>> string1, string2, string3 = '', 'Trondheim', 'Hammer Dance'
>>> non_null = string1 or string2 or string3
>>> non_null
'Trondheim'

即,计算那个表达,就把该表达式赋给等号左边的变量.

6 比较序列和其他类型

序列对象和相同序列类型的其他对象可以比较.这种比较是逐字的.
一个一个对比,而且是递归的
一个序列若是另一个的从头开始的子集,则子集要更小.
字符串的话,则是按照Unicod编码的顺序.例子如下

(1, 2, 3)              < (1, 2, 4)
[1, 2, 3]              < [1, 2, 4]
'ABC' < 'C' < 'Pascal' < 'Python'
(1, 2, 3, 4)           < (1, 2, 4)
(1, 2)                 < (1, 2, -1)
(1, 2, 3)             == (1.0, 2.0, 3.0)
(1, 2, ('aa', 'ab'))   < (1, 2, ('abc', 'a'), 4)

解释器不会给一个任意排序,而是给一个TypeError的异常.

你可能感兴趣的:(重新撸 Python 官方文档02--Tuples, Sets and Dictionaries)