解读The Python Tutorial(五)

5. Data Structures

5.1. More on Lists
>>> fruits = ['orange', 'apple', 'pear', 'banana', 'kiwi', 'apple', 'banana']
>>> fruits.count('apple') #apple出现两次,return 2
2
>>> fruits.count('tangerine')
0
>>> fruits.index('banana') #banana虽然出现两次但第一次是出现在3下标
3
>>> fruits.index('banana', 4)  # index(x[, start[, end]]) 查找下一个,中括号是可选参数
6
>>> fruits.reverse()  #倒序,该方法return none,所以要输入fruits才能看到打印结果
>>> fruits
['banana', 'apple', 'kiwi', 'banana', 'pear', 'apple', 'orange']
>>> fruits.append('grape') #在末尾加元素
>>> fruits
['banana', 'apple', 'kiwi', 'banana', 'pear', 'apple', 'orange', 'grape']
>>> fruits.sort() #从小到大排序
>>> fruits
['apple', 'apple', 'banana', 'banana', 'grape', 'kiwi', 'orange', 'pear']
>>> fruits.pop()  #无参数时,默认删除list末端元素并return该元素
'pear'
5.1.1. Using Lists as Stacks

通过pop和append方法把list当成堆栈(last-in, first-out)使用,效率高。

>>> stack = [3, 4, 5]
>>> stack.append(6)
>>> stack.append(7)
>>> stack
[3, 4, 5, 6, 7]
>>> stack.pop()
7
>>> stack
[3, 4, 5, 6]
>>> stack.pop()
6
>>> stack.pop()
5
>>> stack
[3, 4]
5.1.2. Using Lists as Queues

list也可以当成队列(first-in, first-out)使用,但是效率低。建议用 collections.deque,从两边first-in, first-out都高效率。

>>> from collections import deque
>>> queue = deque(["Eric", "John", "Michael"])
>>> queue.append("Terry")           # Terry arrives
>>> queue.append("Graham")          # Graham arrives
>>> queue.popleft()                 # The first to arrive now leaves
'Eric'
>>> queue.popleft()                 # 删除左边首位元素并返回该元素
'John'
>>> queue                           # Remaining queue in order of arrival
deque(['Michael', 'Terry', 'Graham'])
5.1.3. List Comprehensions

推导式
lsit的生成方式:
通常方法:这种方法有个副作用是list生成后x还一直存在内存。

>>> squares = []
>>> for x in range(10):
...     squares.append(x**2)
...
>>> squares
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

上面同样的list可以用推导生成方式:最外面的中括号表示将生成的是一个list类型,括号里面首先是元素表达式,接着任意个for循环子句或if子句。

squares = [x**2 for x in range(10)]

推荐式更多示例:

>>> [(x, y) for x in [1,2,3] for y in [3,1,4] if x != y] #两个for是嵌套的,第一个是外循环,第二个是内循环。元素表达式是一个元组类型。
[(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]
>>> vec = [-4, -2, 0, 2, 4]
>>> # create a new list with the values doubled
>>> [x*2 for x in vec]
[-8, -4, 0, 4, 8]
>>> # filter the list to exclude negative numbers
>>> [x for x in vec if x >= 0]
[0, 2, 4]
>>> # apply a function to all the elements
>>> [abs(x) for x in vec]
[4, 2, 0, 2, 4]
>>> # call a method on each element
>>> freshfruit = ['  banana', '  loganberry ', 'passion fruit  ']
>>> [weapon.strip() for weapon in freshfruit]
['banana', 'loganberry', 'passion fruit']
>>> # create a list of 2-tuples like (number, square)
>>> [(x, x**2) for x in range(6)]
[(0, 0), (1, 1), (2, 4), (3, 9), (4, 16), (5, 25)]
>>> # the tuple must be parenthesized, otherwise an error is raised
>>> [x, x**2 for x in range(6)]
  File "<stdin>", line 1, in <module>
    [x, x**2 for x in range(6)]
               ^
SyntaxError: invalid syntax
>>> # flatten a list using a listcomp with two 'for'
>>> vec = [[1,2,3], [4,5,6], [7,8,9]]
>>> [num for elem in vec for num in elem]
[1, 2, 3, 4, 5, 6, 7, 8, 9]

>>> from math import pi 
>>> [str(round(pi, i)) for i in range(1, 6)] #这个元素的表达式就比较复杂了
['3.1', '3.14', '3.142', '3.1416', '3.14159']

#元素表达式本身也可以是一个推导式,即内嵌推导式
>>> matrix = [
...     [1, 2, 3, 4],
...     [5, 6, 7, 8],
...     [9, 10, 11, 12],
... ]
>>> [[row[i] for row in matrix] for i in range(4)]  #[row[i] for row in matrix]是元素表达式,同时也是list形式,说明这些元素是list类型。每循环一次for i就计算一次表达式的值
[[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]
#但是表达式改成(row[i] for row in matrix)以期望生成元组,就语法报错,因为元组元素之间是有逗号的。

要实现生成元组的功能刚好有个zip函数是专门生成元组的。zip的参数是任意个list

>>> list(zip(*matrix)) #
[(1, 5, 9), (2, 6, 10), (3, 7, 11), (4, 8, 12)]

>>> x = [1, 2, 3]
>>> y = [4, 5, 6]
>>> zipped = zip(x, y)
>>> list(zipped)
[(1, 4), (2, 5), (3, 6)]
The del statement
>>> a = [-1, 1, 66.25, 333, 333, 1234.5]
>>> del a[0] #与pop不同的是,del return none
>>> a
[1, 66.25, 333, 333, 1234.5]
>>> del a[2:4] #切片式删除
>>> a
[1, 66.25, 1234.5]
>>> del a[:]  #清空整个list
>>> a
[]
>>> del a #删除a变量,比清空a list还厉害。
5.3. Tuples and Sequences
>>> 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 "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment
>>> # but they can contain mutable objects:
... v = ([1, 2, 3], [3, 2, 1])  #但是元组的元素可以是 一些可赋值的类型,比如list
>>> v
([1, 2, 3], [3, 2, 1])


>>> empty = () #新建空元组
>>> singleton = 'hello',    #建立只有一个元素的元组,由于元素必须通过逗号分隔,所以必须有一个逗号在末尾
>>> len(empty)
0
>>> len(singleton)
1
>>> singleton
('hello',)    #输出时,也能看到这个逗号

t = 12345, 54321, 'hello!'
>>> x, y, z = t  #元组的拆分,xyz之间有逗号,xyz值分别为12345, 54321, 'hello!'
5.4. Sets

集合是不重复,无序的。支持数学上的各种交集,并集等运算。通过set()或没有set字样的大括号{}建立。但是空集只能set()建立。

>>> basket = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana'} #通过{}建立
>>> print(basket)                      
{'orange', 'banana', 'pear', 'apple'}  #解释器自动消除重复的元素
>>> 'orange' in basket                 # 判断元素是否属于该集合
True
>>> 'crabgrass' in basket
False

>>> # 通过set()建立集体,元素之间没有逗号。
...
>>> 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'}

集合和list一样支持推导式:

>>> a = {x for x in 'abracadabra' if x not in 'abc'}
>>> a #如果右边表达式用[]括起来生成的就是list了结果就是['r', 'd', 'r'],有重复项了
{'r', 'd'}
5.5. Dictionaries

其实就是一些key:value组合体,这些合体是无序的,但同一个字典内key是唯一的。
通过{}建立空字典,字典的key可以是数字,字符等不可变的数据类型。

>>> tel = {'jack': 4098, 'sape': 4139} #字典通过冒号组合的键值对,与元组的逗号不同。
>>> tel['guido'] = 4127  #字典也很像list
>>> tel
{'sape': 4139, 'guido': 4127, 'jack': 4098} #这些键值对是无序的
>>> tel['jack']
4098
>>> del tel['sape'] #del的一个用法
>>> tel['irv'] = 4127
>>> tel
{'guido': 4127, 'irv': 4127, 'jack': 4098}
>>> list(tel.keys())  #列出的key也是无序的
['irv', 'guido', 'jack']
>>> sorted(tel.keys()) #这样就有序了
['guido', 'irv', 'jack']
>>> 'guido' in tel  #字典的一些用法
True
>>> 'jack' not in tel
False

dict()函数可以提取建值对,建立字典。

>>> dict([('sape', 4139), ('guido', 4127), ('jack', 4098)])
{'sape': 4139, 'jack': 4098, 'guido': 4127}
>>> 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}
5.6. Looping Techniques
#遍历字典时,通过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

#遍历list时,通过enumerate()方法获得下标和元素。
>>> for i, v in enumerate(['tic', 'tac', 'toe']):
...     print(i, v)
...
0 tic
1 tac
2 toe

#通过zip同时遍历多组list。
>>> 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

#通过sort排序遍历
>>> basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']
>>> for f in sorted(set(basket)):
...     print(f)
...
apple
banana
orange
pear
#另外,边遍历边修改时,最好新建一个复本来遍历或修改。
5.7. More on Conditions

与或非这些是“短路”判断,即结果一旦明确,将不会进行后面的判断。

>>> string1, string2, string3 = '', 'Trondheim', 'Hammer Dance'
>>> non_null = string1 or string2 or string3
>>> non_null
'Trondheim'
5.8. Comparing Sequences and Other Types

其他数据类型的比较,

(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)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值