本人以简书作者 SeanCheney 系列专题文章并结合原书为学习资源,记录个人笔记,仅作为知识记录及后期复习所用,原作者地址查看 简书 SeanCheney,如有错误,还望批评指教。——ZJ
原作者:SeanCheney | 链接:https://www.jianshu.com/p/b444cda10aa0 | 來源:简书
Github:wesm | Github:中文 BrambleXu|
简书:利用Python进行数据分析·第2版
环境:Python 3.6
Python的数据结构简单而强大。通晓它们才能成为熟练的Python程序员。
In [1]: tup = 4, 5, 6, 'what'
In [2]: tup
Out[2]: (4, 5, 6, 'what')
In [3]: nested_tup = (4,5,6),(7,8),[2,3,4],'what'
In [4]: nested_tup
Out[4]: ((4, 5, 6), (7, 8), [2, 3, 4], 'what')
In [5]: tuple([4,0,4])
Out[5]: (4, 0, 4)
In [6]: tup = tuple('string')
In [7]: tup
Out[7]: ('s', 't', 'r', 'i', 'n', 'g')
In [8]: tup[2]
Out[8]: 'r'
In [11]: tup = tuple(['foo',[1,2],True])
In [12]: tup[2]
Out[12]: True
In [13]: tup[2] = False
----------------------------------------------------------------
TypeError Traceback (most recent call last)
13-b89d0c4ae599> in <module>()
----> 1 tup[2] = False
TypeError: 'tuple' object does not support item assignment
In [14]: tup[1].append(3)
In [15]: tup
Out[15]: ('foo', [1, 2, 3], True)
In [17]: (4, None, 'foo') + (6,0) + ('bat',)
Out[17]: (4, None, 'foo', 6, 0, 'bat')
In [19]: (4, None, 'foo') + (6,0) + (4,)
Out[19]: (4, None, 'foo', 6, 0, 4)
In [21]: (4,)+(5,6)
Out[21]: (4, 5, 6)
In [22]: ('4', 4, 'bat') * 4
Out[22]: ('4', 4, 'bat', '4', 4, 'bat', '4', 4, 'bat', '4', 4, '
bat')
In [25]: tup = (4,56,{
'X':'X','y':'Y'})
In [26]: a, b, c = tup
In [27]: a
Out[27]: 4
In [28]: b
Out[28]: 56
In [29]: c
Out[29]: {
'X': 'X', 'y': 'Y'}
In [31]: tup = 4,5,(6,7)
In [32]: a,b,c,d = tup
----------------------------------------------------------------
ValueError Traceback (most recent call last)
32-fca040b764b2> in ()
----> 1 a,b,c,d = tup
ValueError: not enough values to unpack (expected 4, got 3)
In [33]: a,b,(c,d) = tup
In [34]: d
Out[34]: 7
In [35]: a,b = 1, 2
In [36]: b, a = a,b
In [37]: a
Out[37]: 2
In [38]: b
Out[38]: 1
In [39]: seq = [(1,2,3),(4,5,6),(7,8,9)]
In [40]: for a, b, c in seq:
...: print('a={0}, b={1}, c={2}'.format(a,b,c))
...:
a=1, b=2, c=3
a=4, b=5, c=6
a=7, b=8, c=9
另一个常见用法是从函数返回多个值。后面会详解。
Python 最近新增了更多高级的元组拆分功能,允许从元组的开头“摘取”几个元素。它使用了特殊的语法 *rest
,这也用在函数签名中以抓取任意长度列表的位置参数, rest 的部分是想要舍弃的部分,rest 的名字不重要。作为惯用写法,许多 Python程序员会将不需要的变量使用下划线:
In [41]: values = 1,2,3,4,5
In [42]: a, b, *rest = values
In [43]: rest
Out[43]: [3, 4, 5]
In [44]: a, b, *_ = values
In [45]: _
Out[45]: [3, 4, 5]
In [48]: a = (1,2,2,2,3,3,4,5)
In [49]: a
Out[49]: (1, 2, 2, 2, 3, 3, 4, 5)
In [50]: a.count(2)
Out[50]: 3
In [42]: gen = range(10)
In [43]: gen
Out[43]: range(0, 10)
In [44]: list(gen)
Out[44]: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
In [47]: b_list.insert(1, 'red')
In [48]: b_list
Out[48]: ['foo', 'red', 'peekaboo', 'baz', 'dwarf']
警告:与append相比,insert耗费的计算量大,因为对后续元素的引用必须在内部迁移,以便为新元素提供空间。如果要在序列的头部和尾部插入元素,你可能需要使用collections.deque,一个双尾部队列。
insert 的逆运算是 pop,它移除并返回指定位置的元素:
In [55]: b_list = [2,3,4,5]
In [56]: b_list.insert(1,5)
In [57]: b_list
Out[57]: [2, 5, 3, 4, 5]
In [58]: b_list.pop(3)
Out[58]: 4
In [59]: b_list
Out[59]: [2, 5, 3, 5]
In [60]: a_list = ['foo','wa', 'ten', 'foo']
In [61]: a_list.remove('foo')
In [62]: a_list
Out[62]: ['wa', 'ten', 'foo']
In [63]: a_list.remove('foo')
In [65]: a_list
Out[65]: ['wa', 'ten']
In [73]: a_list
Out[73]: ['wa', 'ten', 'look', 'time']
In [74]: 'tn' in a_list
Out[74]: False
In [75]: 'ten' in a_list
Out[75]: True
In [76]: 'ten' not in a_list
Out[76]: False
In [77]: [4, None, 'foo'] + [7, 8, (2,3)]
Out[77]: [4, None, 'foo', 7, 8, (2, 3)]
In [78]: x = [4,5,6,None,'foo']
In [80]: x.extend([7, 8, 90,(3,4)])
In [81]: x
Out[81]: [4, 5, 6, None, 'foo', 7, 8, 90, (3, 4)]
everything = []
for chunk in list_of_lists:
everything.extend(chunk)
In [86]: a = [7,3,8,4,6,1,9,2]
In [87]: a.sort()
In [88]: a
Out[88]: [1, 2, 3, 4, 6, 7, 8, 9]
In [89]: b = ['ipyhon','python','list','set']
In [90]: b.sort()
In [91]: b
Out[91]: ['ipyhon', 'list', 'python', 'set']
In [92]: b.sort(key=len)
In [93]: b
Out[93]: ['set', 'list', 'ipyhon', 'python']
bisect
模块支持二分查找,和向已排序的列表插入值。bisect.bisect
可以找到插入值后仍保证排序的位置,bisect.insort
是向这个位置插入值:In [94]: import bisect
In [95]: c = [1, 2, 2, 2, 3, 4, 7]
In [96]: bisect.bisect(c,2) # 意思是,如果将 2 这个数字插入进去,将排在索引值 为 4 的位置
Out[96]: 4
In [97]: bisect.bisect(c,5) # 意思是,如果将 2 这个数字插入进去,将排在索引值 为 6 的位置
Out[97]: 6
In [98]: bisect.insort(c,6)
In [99]: c
Out[99]: [1, 2, 2, 2, 3, 4, 6, 7]
bisect
模块不会检查列表是否已排好序,进行检查的话会耗费大量计算。因此,对未排序的列表使用bisect
不会产生错误,但结果不一定正确。start:stop
:In [100]: seq = [7,2,3,4,5,7,3,4,5]
In [101]: seq[1:4]
Out[101]: [2, 3, 4]
In [106]: seq[1:2] = [9,9]
In [107]: seq
Out[107]: [7, 9, 9, 4, 3, 3, 4, 5, 7, 3, 4, 5]
In [5]: seq = [1,2,3,4,5,6,7,8,9]
In [6]: seq[:6]
Out[6]: [1, 2, 3, 4, 5, 6]
In [7]: seq[-4:]
Out[7]: [6, 7, 8, 9]
In [8]: seq[-1]
Out[8]: 9
In [9]: seq[-2]
Out[9]: 8
In [10]: seq[-6:-2]
Out[10]: [4, 5, 6, 7]
In [11]: seq[::2]
Out[11]: [1, 3, 5, 7, 9]
In [12]: seq[::-1]
Out[12]: [9, 8, 7, 6, 5, 4, 3, 2, 1]
i = 0
for value in collection:
# do something with value
i += 1
for i, value in enumerate(collection):
# do something with value
enumerate
的一个好方法是计算序列(唯一的)dict
映射到位置的值:In [18]: some_list = ['foo', 'iii', 'waz']
In [19]: mapping = {}
In [20]: for i, v in enumerate(some_list):
...: mapping[v] = i
...:
In [21]: mapping
Out[21]: {
'foo': 0, 'iii': 1, 'waz': 2}
sorted 函数可以从任意序列的元素返回一个新的排好序的列表,sorted
函数可以接受和 sort 相同的参数。
In [87]: sorted([7, 1, 2, 6, 0, 3, 2])
Out[87]: [0, 1, 2, 2, 3, 6, 7]
In [88]: sorted('horse race')
Out[88]: [' ', 'a', 'c', 'e', 'e', 'h', 'o', 'r', 'r', 's']
In [22]: seq1 = ['foo', 'bar', 'baz']
In [23]: seq2 = ['one', 'two', 'three']
In [24]: zipped = zip(seq1, seq2)
In [25]: zipped
Out[25]: 0x23ba9550e88>
In [26]: list(zipped)
Out[26]: [('foo', 'one'), ('bar', 'two'), ('baz', 'three')]
In [27]: seq3 = [False, True]
In [28]: list(zip(seq1, seq2, seq3))
Out[28]: [('foo', 'one', False), ('bar', 'two', True)]
zip
的常见用法之一是同时迭代多个序列,可能结合 enumerate
使用:
In [29]: for i , (a,b) in enumerate(zip(seq1,seq2)):
...: print('{0}:{1},{2}'.format(i, a,b))
...:
0:foo,one
1:bar,two
2:baz,three
zip
可以被用来解压序列。也可以当作把行的列表转换为列的列表。这个方法看起来有点神奇:In [30]: pitchers = [('Nolan', 'Ryan'),('Roger', 'Clemens'),('S
...: chilling', 'Curt')]
In [31]: fisrt_names, last_names = zip(*pitchers)
In [32]: fisrt_names
Out[32]: ('Nolan', 'Roger', 'Schilling')
In [33]: last_names
Out[33]: ('Ryan', 'Clemens', 'Curt')
reversed
可以从后向前迭代一个序列,要记住reversed是一个生成器(后面详细介绍),只有实体化(即列表或for循环)之后才能创建翻转的序列。In [100]: list(reversed(range(10)))
Out[100]: [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
字典可能是 Python 最为重要的数据结构。它更为常见的名字是哈希映射或关联数组。它是键值对的大小可变集合,键和值都是 Python 对象。创建字典的方法之一是使用尖括号,用冒号分隔键和值
你可以像访问列表或元组中的元素一样,访问、插入或设定字典中的元素
In [34]: empty_dict = {}
In [35]: d1 = {
'a':'some value','b':[1,2,3,4]}
In [36]: d1
Out[36]: {
'a': 'some value', 'b': [1, 2, 3, 4]}
In [37]: d1[7] = 'an integer'
In [38]: d1
Out[38]: {
7: 'an integer', 'a': 'some value', 'b': [1, 2, 3, 4]}
In [40]: d1['b']
Out[40]: [1, 2, 3, 4]
In [41]: 'b' in d1
Out[41]: True
In [42]: d1[5] = 'some value'
In [43]: d1
Out[43]: {
5: 'some value', 7: 'an integer', 'a': 'some value', 'b':
[1, 2, 3, 4]}
In [44]: d1['dummy'] = 'another value'
In [45]: d1
Out[45]:
{
5: 'some value',
7: 'an integer',
'a': 'some value',
'b': [1, 2, 3, 4],
'dummy': 'another value'}
In [46]: del d1[5]
In [47]: d1
Out[47]:
{
7: 'an integer',
'a': 'some value',
'b': [1, 2, 3, 4],
'dummy': 'another value'}
In [48]: ret = d1.pop('dummy')
In [49]: ret
Out[49]: 'another value'
In [50]: d1
Out[50]: {
7: 'an integer', 'a': 'some value', 'b': [1, 2, 3, 4]}
keys
和values
是字典的键和值的迭代器方法。虽然键值对没有顺序,这两个方法可以用相同的顺序输出键和值:In [51]: d1.keys()
Out[51]: dict_keys(['a', 'b', 7])
In [52]: list(d1.keys())
Out[52]: ['a', 'b', 7]
In [53]: list(d1.values())
Out[53]: ['some value', [1, 2, 3, 4], 'an integer']
update
方法可以将一个字典与另一个融合,update
方法是原地改变字典,因此任何传递给update
的键的旧的值都会被舍弃In [54]: mapping = {}
In [55]: for key, value in zip(key_list, value_list):
...: mapping[key] = value
In [56]: mapping = dict(zip(range(5), reversed(range(5))))
In [57]: mapping
Out[57]: {
0: 4, 1: 3, 2: 2, 3: 1, 4: 0}
dict
的方法get
和pop
可以取默认值进行返回,if-else
语句可以简写成第二个:if key in some_dict:
value = some_dict[key]
else:
value = default_value
# 简写
value = some_dict.get(key, default_value)
get
默认会返回None
,如果不存在键,pop
会抛出一个例外。关于设定值,常见的情况是在字典的值是属于其它集合,如列表。例如,你可以通过首字母,将一个列表中的单词分类:In [58]: words = ['apple', 'bat', 'bar', 'atom', 'book']
In [59]: by_letter = {}
In [60]: for word in words:
...: letter = word[0]
...: if letter not in by_letter:
...: by_letter[letter] = [word]
...: else:
...: by_letter[letter].append(word)
...:
In [61]: by_letter
Out[61]: {
'a': ['apple', 'atom'], 'b': ['bat', 'bar', 'book']}
setdefault
方法就正是干这个的。前面的for
循环可以改写为:In [62]: for word in words:
...: letter = word[0]
...: by_letter.setdefault(letter,[]).append(word)
...:
collections
模块有一个很有用的类,defaultdict
,它可以进一步简化上面。传递类型或函数以生成每个位置的默认值:In [65]: from collections import defaultdict
In [66]: by_letter = defaultdict(list)
In [67]: for word in words:
...: by_letter[word[0]].append(word)
In [68]: by_letter
Out[68]: defaultdict(list, {
'a': ['apple', 'atom'], 'b': ['bat', 'bar', 'book']})
In [69]: hash('string')
Out[69]: -2802364732335948762
In [70]: hash((1,2,(2,3)))
Out[70]: 1097636502276347782
In [71]: hash(([2,3,4],'fail'))
-------------------------------------------------------------------
TypeError Traceback (most recent call last)
71-18105c851885> in ()
----> 1 hash(([2,3,4],'fail'))
TypeError: unhashable type: 'list'
In [72]: d = {}
In [73]: d[tuple([1, 2, 3])] = 5
In [74]: d
Out[74]: {(1, 2, 3): 5}
set
函数或使用花(尖)括号 set
语句:In [75]: set([2,2,2,3,3,3,4,5,6])
Out[75]: {
2, 3, 4, 5, 6}
In [76]: {
3,3,3,3,4,4,56,7,78,8}
Out[76]: {
3, 4, 7, 8, 56, 78}
union
方法,或者|
运算符,交集的元素包含在两个集合中。可以用 intersection
或 &
运算符:In [77]: a = {1,2, 3,4,5}
In [78]: b = {3,4,5,6,7,8}
In [79]: a.union(b)
Out[79]: {1, 2, 3, 4, 5, 6, 7, 8}
In [80]: a | b # 并集
Out[80]: {1, 2, 3, 4, 5, 6, 7, 8}
In [81]: # 交集
In [82]: a.intersection(b)
Out[82]: {3, 4, 5}
In [83]: a & b
Out[83]: {3, 4, 5}
常用的集合方法。
In [84]: c = a.copy()
In [85]: c |= b
In [86]: c
Out[86]: {1, 2, 3, 4, 5, 6, 7, 8}
In [87]: d = a.copy()
In [88]: d &= b
In [89]: d
Out[89]: {3, 4, 5}
In [90]: my_data = [1,2,3,4]
In [91]: my_set = {tuple(my_data)}
In [92]: my_set
Out[92]: {(1, 2, 3, 4)}
In [93]: a_set = {1,2,3,4,5}
In [94]: {1,2,3}.issubset(a_set)
Out[94]: True
In [95]: a_set.issuperset({1,2,3})
Out[95]: True
In [97]: {1,2,3} == {2,3,1}
Out[97]: True
[expr for val in collection if condition]
result = []
for val in collection:
if condition:
result.append(expr)
filter
条件可以被忽略,只留下表达式就行。例如,给定一个字符串列表,我们可以过滤出长度在 2 及以下的字符串,并将其转换成大写:In [98]: strings = ['a', 'as', 'bat', 'car', 'dove', 'python']
...:
In [99]: [x.upper() for x in strings if len(x) > 2]
Out[99]: ['BAT', 'CAR', 'DOVE', 'PYTHON']
dict_comp = {key-expr : value-expr for value in collection if condition}
set_comp = {expr for value in collection if condition}
In [1]: strings = ['a', 'as', 'bat', 'car', 'dove', 'python']
In [2]: unique_lengths = {len(x) for x in strings}
In [3]: unique_lengths
Out[3]: {1, 2, 3, 4, 6}
map
函数可以进一步简化:In [4]: set(map(len, strings))
Out[4]: {
1, 2, 3, 4, 6}
In [5]: loc_mapping = {val:index for index, val in enumerate(st
...: rings)}
In [6]: loc_mapping
Out[6]: {
'a': 0, 'as': 1, 'bat': 2, 'car': 3, 'dove': 4, 'python
': 5}
In [7]: strings
Out[7]: ['a', 'as', 'bat', 'car', 'dove', 'python']
e
。可以用for
循环来做:In [8]: all_data = [['John', 'Emily', 'Michael', 'Mary', 'Steve
...: n'],['Maria', 'Juan', 'Javier', 'Natalia', 'Pilar']]
InIn [9]: names__interest = []
In [10]: for names in all_data:
...: enough_es = [name for name in names if name.count(
...: 'e') >=2]
...: names__interest.extend(enough_es)
...:
In [11]: names__interest
Out[11]: ['Steven']
In [12]: result = [name for names in all_data for name in names
...: if name.count('e') >= 2]
In [13]: result
Out[13]: ['Steven']
for
部分是根据嵌套的顺序,过滤条件还是放在最后。下面是另一个例子,我们将一个整数元组的列表扁平化成了一个整数列表:In [14]: some_tuples = [(1,2,3),(4,5,6),(7,8,9)]
In [15]: flattend = [x for tup in some_tuples for x in tup]
In [16]: flattend
Out[16]: [1, 2, 3, 4, 5, 6, 7, 8, 9]
for
表达式的顺序是与嵌套for
循环的顺序一样(而不是列表推导式的顺序):flattened = []
for tup in some_tuples:
for x in tup:
flattened.append(x)
In [17]: [[x for x in tup] for tup in some_tuples]
Out[17]: [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
函数是 Python 中最主要也是最重要的代码组织和复用手段。作为最重要的原则,如果你要重复使用相同或非常类似的代码,就需要写一个函数。通过给函数起一个名字,还可以提高代码的可读性。
def
关键字声明,用 return
关键字返回值:def my_function(x, y, z=1.5):
if z > 1:
return z * (x + y)
else:
return z / (x + y)
同时拥有多条return
语句也是可以的。如果到达函数末尾时没有遇到任何一条return
语句,则返回None
。
my_function(5, 6, z=0.7)
my_function(3.14, 7, 3.5)
my_function(10, 20)
函数可以访问两种不同作用域中的变量:全局(global)和局部(local)。Python有一种更科学的用于描述变量作用域的名称,即命名空间(namespace)。任何在函数中赋值的变量默认都是被分配到局部命名空间(local namespace)中的。局部命名空间是在函数被调用时创建的,函数参数会立即填入该命名空间。在函数执行完毕之后,局部命名空间就会被销毁(会有一些例外的情况,具体请参见后面介绍闭包的那一节)。看看下面这个函数:
def func():
a = []
for i in range(5):
a.append(i)
func()
之后,首先会创建出空列表 a,然后添加 5 个元素,最后 a 会在该函数退出的时候被销毁。假如我们像下面这样定义 a:a = []
def func():
for i in range(5):
a.append(i)
In [168]: a = None
In [169]: def bind_a_variable():
.....: global a
.....: a = []
.....: bind_a_variable()
.....:
In [170]: print(a)
一个很好的功能是:函数可以返回多个值。下面是一个简单的例子:
def f():
a = 5
b = 6
c = 7
return a, b, c
a, b, c = f()
return_value = f()
return_value
将会是一个含有 3 个返回值的三元元组。此外,还有一种非常具有吸引力的多值返回方式——返回字典:def f():
a = 5
b = 6
c = 7
return {
'a' : a, 'b' : b, 'c' : c}
由于 Python 函数都是对象,因此,在其他语言中较难表达的一些设计思想在 Python 中就要简单很多了。假设我们有下面这样一个字符串数组,希望对其进行一些数据清理工作并执行一堆转换:
In [18]: states = [' Alabama ', 'Georgia!', 'Georgia', 'georg
...: ia', 'FlOrIda', 'south carolina##', 'West virginia?'
...: ]
re
模块:In [19]: import re
In [20]: def clean_strings(strings):
...: result = []
...: for value in strings:
...: value = value.strip()
...: value = re.sub('[!#?]', '', value)
...: value = value.title()
...: result.append(value)
...: return result
...:
In [22]: clean_strings(states)
Out[22]:
['Alabama',
'Georgia',
'Georgia',
'Georgia',
'Florida',
'South Carolina',
'West Virginia']
In [23]: def remove_punctuation(value):
...: return re.sub('[!#?]', '', value)
...:
In [24]: clean_ops = [str.strip, remove_punctuation, str.title]
...:
In [26]: def clean_strings(strings, ops):
...: result = []
...: for value in strings:
...: for function in ops:
...: value = function(value)
...: result.append(value)
...: return result
...:
In [27]: clean_strings(states, clean_ops)
Out[27]:
['Alabama',
'Georgia',
'Georgia',
'Georgia',
'Florida',
'South Carolina',
'West Virginia']
这种多函数模式使你能在很高的层次上轻松修改字符串的转换方式。此时的clean_strings 也更具可复用性!
还可以将函数用作其他函数的参数,比如内置的map
函数,它用于在一组数据上应用一个函数:
In [28]: for x in map(remove_punctuation, states):
...: print(x)
...:
Alabama
Georgia
Georgia
georgia
FlOrIda
south carolina
West virginia
Python 支持一种被称为匿名的、或 lambda 函数。它仅由单条语句组成,该语句的结果就是返回值。它是通过 lambda 关键字定义的,这个关键字没有别的含义,仅仅是说“我们正在声明的是一个匿名函数”。
In [29]: def short_function(x):
...: return x * 2
...:
In [30]: equiv_anon = lambda x: x * 2
In [31]: equiv_anon
Out[31]: <function __main__.>
In [32]: equiv_anon(5)
Out[32]: 10
In [33]: def apply_to_list(some_list, f):
...: return [f(x) for x in some_list]
...:
In [34]: ints = [4, 0, 1, 5, 6]
In [35]: apply_to_list(ints, lambda x:x * 2)
Out[35]: [8, 0, 2, 10, 12]
虽然你可以直接编写[x *2for x in ints]
,但是这里我们可以非常轻松地传入一个自定义运算给apply_to_list
函数。
In [36]: strings = ['foo', 'card', 'bar', 'aaaa', 'abab']
In [37]: strings.sort(key=lambda x:len(set(list(x))))
In [38]: strings
Out[38]: ['aaaa', 'foo', 'abab', 'bar', 'card']
lambda
函数之所以会被称为匿名函数,与def
声明的函数不同,原因之一就是这种函数对象本身是没有提供名称name
属性。柯里化(currying)是一个有趣的计算机科学术语,它指的是通过“部分参数应用”(partial argument application)从现有函数派生出新函数的技术。例如,假设我们有一个执行两数相加的简单函数,通过这个函数,我们可以派生出一个新的只有一个参数的函数——add_five,它用于对其参数加 5:
In [39]: def add_numbers(x,y):
...: return x + y
...:
In [40]: add_five = lambda y: add_numbers(5,y)
In [41]: add_five(10)
Out[41]: 15
add_numbers
的第二个参数称为“柯里化的”(curried)。这里没什么特别花哨的东西,因为我们其实就只是定义了一个可以调用现有函数的新函数而已。内置的functools
模块可以用partial
函数将此过程简化:
In [42]: from functools import partial
In [43]: add_five = partial(add_numbers, 5)
In [44]: add_five(22)
Out[44]: 27
能以一种一致的方式对序列进行迭代(比如列表中的对象或文件中的行)是Python的一个重要特点。这是通过一种叫做迭代器协议(iterator protocol,它是一种使对象可迭代的通用方式)的方式实现的,一个原生的使对象可迭代的方法。比如说,对字典进行迭代可以得到其所有的键:
In [180]: some_dict = {
'a': 1, 'b': 2, 'c': 3}
In [181]: for key in some_dict:
.....: print(key)
a
b
c
for key in some_dict
时,Python 解释器首先会尝试从some_dict
创建一个迭代器:In [182]: dict_iterator = iter(some_dict)
In [183]: dict_iterator
Out[183]: 0x7fbbd5a9f908>
for
循环之类的上下文中向 Python
解释器输送对象。大部分能接受列表之类的对象的方法也都可以接受任何可迭代对象。比如min、max、sum
等内置方法以及 list、tuple
等类型构造器:In [184]: list(dict_iterator)
Out[184]: ['a', 'b', 'c']
return
替换为yeild
即可:In [45]: def squares(n=10):
...: print('Generating squares from 1 to {0}'.format(n
...: ** 2))
...: for i in range(1, n + 1):
...: yield i ** 2
...:
In [46]: gen = squares() # 调用该生成器时,没有任何代码会被立即执行:
In [47]: gen
Out[47]: 0x000002088B669CA8>
# 直到你从该生成器中请求元素时,它才会开始执行其代码:
In [48]: for x in gen:
...: print(x, end= " ")
...:
Generating squares from 1 to 100
1 4 9 16 25 36 49 64 81 100
另一种更简洁的构造生成器的方法是使用生成器表达式(generator expression)。这是一种类似于列表、字典、集合推导式的生成器。其创建方式为,把列表推导式两端的方括号改成圆括号:
In [49]: gen = (x**2 for x in range(100))
In [50]: gen
Out[50]: at 0x000002088AFDFDB0>
# 它跟下面这个冗长得多的生成器是完全等价的:
In [51]: def _make_gen():
...: for x in range(100):
...: yield x **2
...:
In [52]: gen = _make_gen()
In [54]: sum(x **2 for x in range(100))
Out[54]: 328350
In [55]: dict((i, i**2) for i in range(5))
Out[55]: {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
标准库tertools
块中有一组用于许多常见数据算法的生成器。例如,roupby
以接受任何序列和一个函数。它根据函数的返回值对序列中的连续元素进行分组。下面是一个例子:
In [56]: import itertools
In [57]: first_letter = lambda x:x[0]
In [58]: names = ['Alan', 'Adam','Wes', 'Will', 'Albert', 'Stev
...: en']
In [59]: for letter, names in itertools.groupby(names, first_le
...: tter):
...: print(letter, list(names))
...:
A ['Alan', 'Adam']
W ['Wes', 'Will']
A ['Albert']
S ['Steven']
tertools
函数优雅地处理 Python 的错误和异常是构建健壮程序的重要部分。在数据分析中,许多函数函数只用于部分输入。例如,Python 的 float 函数可以将字符串转换成浮点数,但输入有误时,有 ValueError 错误:
In [60]: float('1.2345')
Out[60]: 1.2345
In [61]: float('something')
----------------------------------------------------------------
ValueError Traceback (most recent call last)
input -61-2649e4ade0e6> in <module>()
----> 1 float('something')
ValueError: could not convert string to float: 'something'
float
的错误,让它返回输入值。我们可以写一个函数,在try/except
中调用float
,当float(x)
抛出异常时,才会执行except
的部分,你可能注意到float
抛出的异常不仅是ValueError
:In [62]: def attempt_float(x):
...: try:
...: return float(x)
...: except:
...: return x
...:
In [63]: attempt_float('2.2222')
Out[63]: 2.2222
In [64]: attempt_float('nothing')
Out[64]: 'nothing'
In [65]: float((1,2))
----------------------------------------------------------------
TypeError Traceback (most recent call last)
65-a101b3a3d6cd> in ()
----> 1 float((1,2))
TypeError: float() argument must be a string or a number, not 't
uple'
ValueError
,TypeError
错误(输入不是字符串或数值)可能是合理的bug
。可以写一个异常类型:
In [66]: def attempt_float(x):
...: try:
...: return float(x)
...: except ValueError:
...: return x
...:
In [67]: attempt_float((1,2))
----------------------------------------------------------------
TypeError Traceback (most recent call last)
67-102527222085> in ()
----> 1 attempt_float((1,2))
66-5a7c37ce098e> in attempt_float(x)
1 def attempt_float(x):
2 try:
----> 3 return float(x)
4 except ValueError:
5 return x
TypeError: float() argument must be a string or a number, not 't
uple'
try
部分的代码是否成功,都执行一段代码。可以使用finally
:In [68]: def attempt_float(x):
...: try:
...: return float(x)
...: except (TypeError, ValueError):
...: return x
# 这里,文件处理 f 总会被关闭。相似的,你可以用 else 让只在 try 分成功的情况 下,才执行代码:
In [72]: path = "./01_practice.py"
In [73]: f = open(path, 'w')
In [74]: try:
...: write_to_file(f)
...: except:
...: print('Failed')
...: else:
...: print('Succeeded')
...: finally:
...: f.close()
...:
Failed
如果是在%run
一个脚本或一条语句时抛出异常,IPython
默认会打印完整的调用栈(traceback),在栈的每个点都会有几行上下文:
In [10]: %run examples/ipython_bug.py
---------------------------------------------------------------------------
AssertionError Traceback (most recent call last)
/home/wesm/code/pydata-book/examples/ipython_bug.py in <module>()
13 throws_an_exception()
14
---> 15 calling_things()
/home/wesm/code/pydata-book/examples/ipython_bug.py in calling_things()
11 def calling_things():
12 works_fine()
---> 13 throws_an_exception()
14
15 calling_things()
/home/wesm/code/pydata-book/examples/ipython_bug.py in throws_an_exception()
7 a = 5
8 b = 6
----> 9 assert(a + b == 10)
10
11 def calling_things():
AssertionError:
自身就带有文本是相对于 Python 标准解释器的极大优点。你可以用魔术命令 %xmode
,从Plain
(与 Python 标准解释器相同)到 Verbose(带有函数的参数值)控制文本显示的数量。后面可以看到,发生错误之后,(用%debug
或%pdb magics
)可以进入stack
进行事后调试。
本书的代码示例大多使用诸如pandas.read_csv
之类的高级工具将磁盘上的数据文件读入Python
数据结构。但我们还是需要了解一些有关 Python 文件处理方面的基础知识。好在它本来就很简单,这也是 Python 在文本和文件处理方面的如此流行的原因之一。
# 为了打开一个文件以便读写,可以使用内置的 open 函数以及一个相对或绝对的文件路径:
In [84]: path = "./test/01_practice.py"
In [85]: f = open(path)
# 默认情况下,文件是以只读模式('r')打开的。然后,我们就可以像处理列表那样来处理这个文件句柄f了,比如对行进行迭代:
In [86]: for line in f:
...: pass
...:
# 从文件中取出的行都带有完整的行结束符(EOL),因此你常常会看到下面这样的代码(得到一组没有 EOL 的行)
In [87]: lines = [x.rstrip() for x in open(path)]
In [88]: lines
Out[88]:
['what a great day 1',
'',
'what a great day 2',
'',
'what a great day 3',
'',
'what a great day 4',
'',
'what a great day 5',
'',
'what a great day 6',
'',
'what a great day 7',
'what a great day 8',
'what a great day 9',
'what a great day 10']
f.close()
In [212]: with open(path) as f:
.....: lines = [x.rstrip() for x in f]
如果输入f =open(path,'w')
,就会有一个新文件被创建在examples/segismundo.txt
,并覆盖掉该位置原来的任何数据。另外有一个x文件模式,它可以创建可写的文件,但是如果文件路径存在,就无法创建。表3-3列出了所有的读/写模式。
read、seek
和tell
。read
会从文件返回字符。字符的内容是由文件的编码决定的(如 UTF-8),如果是二进制模式打开的就是原始字节:In [90]: f = open(path)
In [91]: f.read(10)
Out[91]: 'what a gre'
In [92]: f2 = open(path, 'rb') # Binary mode
In [93]: f2.read(10)
Out[93]: b'what a gre'
In [94]: # read 模式会将文件句柄的位置提前,提前的数量是读取的字
...: 节数。tell 可以给出当前的位置:
In [95]: f.tell()
Out[95]: 10
In [96]: f2.tell()
Out[96]: 10
In [97]:
In [97]: import sys
In [98]: sys.getdefaultencoding()
Out[98]: 'utf-8'
In [99]: # seek 将文件位置更改为文件中的指定字节:
In [100]: f.seek(3)
Out[100]: 3
In [101]: f.read(1)
Out[101]: 't'
In [102]: f.close()
In [103]: f2.close()
write
或writelines
方法。例如,我们可以创建一个无空行版的 prof_mod.py
:
In [104]: with open('tmp.txt', 'w') as handle:
...: handle.writelines(x for x in open(path) if len(x)
...: > 1)
...:
In [105]: with open('tmp.txt') as f:
...: lines = f.readlines()
...:
In [106]: lines
Out[106]:
['what a great day 1 \n',
'what a great day 2 \n',
'what a great day 3 \n',
'what a great day 4 \n',
'what a great day 5 \n',
'what a great day 6 \n',
'what a great day 7 \n',
'what a great day 8 \n',
'what a great day 9 \n',
'what a great day 10 \n']
Python 文件的默认操作是“文本模式”,也就是说,你需要处理 Python 的字符串(即 Unicode)。它与“二进制模式”相对,文件模式加一个 b。我们来看上一节的文件(UTF-8 编码、包含非 ASCII 字符):
In [107]: with open(path) as f:
...: chars = f.read(10)
...:
In [108]: chars
Out[108]: 'what a gre'
In [109]: with open(path,'rb') as f:
...: data = f.read(10)
...:
In [110]: data
Out[110]: b'what a gre'
str
对象,但只有当每个编码的Unicode 字符都完全成形时才能这么做:In [109]: with open(path,'rb') as f:
...: data = f.read(10)
...:
In [110]: data
Out[110]: b'what a gre'
In [111]: data.decode('utf-8')
Out[111]: 'what a gre'
In [112]: data[:4].decode('utf-8')
Out[112]: 'what'
原文章中:
In [234]: data.decode('utf8')
Out[234]: 'Sueña el '
In [235]: data[:4].decode('utf8')
---------------------------------------------------------------------------
UnicodeDecodeError Traceback (most recent call last)
235-300e0af10bb7> in ()
----> 1 data[:4].decode('utf8')
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xc3 in position 3: unexpecte
d end of data
In [113]: sink_path = 'sink.txt'
In [114]: with open(path) as source:
...: with open(sink_path, 'xt', encoding='iso-8859-1')
...: as sink:
...: sink.write(source.read())
...:
In [115]: with open(sink_path, encoding='iso-8859-1') as f:
...: print(f.read(10))
...:
what a gre
In [123]: f = open(path)
In [124]: f.read(10)
Out[124]: 'what a gre'
In [125]: f.seek(7)
Out[125]: 7
In [126]: f.read(1)
Out[126]: 'g'
In [127]: f.close()
原文章中:
In [240]: f = open(path)
In [241]: f.read(5)
Out[241]: 'Sueña'
In [242]: f.seek(4)
Out[242]: 4
In [243]: f.read(1)
---------------------------------------------------------------------------
UnicodeDecodeError Traceback (most recent call last)
243-7841103e33f5> in <module>()
----> 1 f.read(1)
/miniconda/envs/book-env/lib/python3.6/codecs.py in decode(self, input, final)
319 # decode input (taking the buffer into account)
320 data = self.buffer + input
--> 321 (result, consumed) = self._buffer_decode(data, self.errors, final
)
322 # keep undecoded input until the next call
323 self.buffer = data[consumed:]
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xb1 in position 0: invalid s
tart byte
In [244]: f.close()
我们已经学过了 Python 的基础、环境和语法,接下来学习 NumPy 和 Python 的面向数组计算。