Dict 哈希表
Python 的高效键/值哈希表结构称为“字典”。字典的内容可以写为带有大括号 { } 的一系列键值对,例如 dict = {key1:value1, key2:value2, ... }。“空字典”只是一对空的大括号 { }。
在字典中查找或设置值需要使用方括号,例如 dict['foo'] 用于查找键“foo”下的值。字符串、数字和元组用作键,任何类型都可以是值。其他类型可能也可能无法正确用作键(字符串和元组是不可变的,因此它们可以正常发挥作用)。查找不在字典中的值会引发 KeyError - 可以使用“in”检查该键是否在字典中;也可以使用 dict.get(key)(如果相应键不存在,则返回值)或 None(如果键不存在,则使用 get(key, not-found) 来指定要在未找到的情况下返回的值)。
## Can build up a dict by starting with the empty dict {} ## and storing key/value pairs into the dict like this: ## dict[key] = value-for-that-key dict = {} dict['a'] = 'alpha' dict['g'] = 'gamma' dict['o'] = 'omega' print(dict) ## {'a': 'alpha', 'o': 'omega', 'g': 'gamma'} print(dict['a']) ## Simple lookup, returns 'alpha' dict['a'] = 6 ## Put new key/value into dict 'a' in dict ## True ## print(dict['z']) ## Throws KeyError if 'z' in dict: print(dict['z']) ## Avoid KeyError print(dict.get('z')) ## None (instead of KeyError)
默认情况下,字典上的 for 循环会对其键进行迭代。键会以任意顺序显示。dict.keys() 和 dict.values() 方法会明确返回键或值的列表。此外,还有一个 items(),它会返回(键、值)元组列表,这是检查字典中所有键值数据的最有效方法。可以将所有这些列表传递给排序函数。
## By default, iterating over a dict iterates over its keys. ## Note that the keys are in a random order. for key in dict: print(key) ## prints a g o ## Exactly the same as above for key in dict.keys(): print(key) ## Get the .keys() list: print(dict.keys()) ## dict_keys(['a', 'o', 'g']) ## Likewise, there's a .values() list of values print(dict.values()) ## dict_values(['alpha', 'omega', 'gamma']) ## Common case -- loop over the keys in sorted order, ## accessing each key/value for key in sorted(dict.keys()): print(key, dict[key]) ## .items() is the dict expressed as (key, value) tuples print(dict.items()) ## dict_items([('a', 'alpha'), ('o', 'omega'), ('g', 'gamma')]) ## This loop syntax accesses the whole dict by looping ## over the .items() tuple list, accessing one (key, value) ## pair on each iteration. for k, v in dict.items(): print(k, '>', v) ## a > alpha o > omega g > gamma
策略说明:从性能的角度来看,字典是您最好的工具之一,应尽可能使用它来轻松整理数据。例如,您可以读取一个日志文件,其中每行都以 IP 地址开头,并将 IP 地址作为键,并将出现的行列表作为值,将数据存储到字典中。读完整个文件后,您可以查询任何 IP 地址,并立即看到其行列表。字典会接收分散的数据,并将其变为连贯的内容。
Dict 格式设置
% 运算符可方便地按名称将字典中的值替换为字符串:
h = {} h['word'] = 'garfield' h['count'] = 42 s = 'I want %(count)d copies of %(word)s' % h # %d for int, %s for string # 'I want 42 copies of garfield' # You can also use str.format(). s = 'I want {count:d} copies of {word}'.format(h)
Del
“del”运算符执行删除操作。在最简单的情况下,它可以移除变量的定义,就好像该变量尚未定义一样。Del 也可对列表元素或切片使用,以删除列表的相应部分以及从字典中删除条目。
var = 6 del var # var no more! list = ['a', 'b', 'c', 'd'] del list[0] ## Delete first element del list[-2:] ## Delete last two elements print(list) ## ['b'] dict = {'a':1, 'b':2, 'c':3} del dict['b'] ## Delete 'b' entry print(dict) ## {'a':1, 'c':3}
文件
open() 函数会打开并返回文件句柄,此句柄可用于按常规方式读取或写入文件。代码 f = open('name', 'r') 打开文件到变量 f 中,准备执行读取操作,完成后使用 f.close()。用“w”表示写入,使用“a”表示附加,而不是“r”。标准的 for 循环适用于文本文件,遍历文件行(这只适用于文本文件,不适用于二进制文件)。for 循环技术可用来轻松高效地查看文本文件中的所有行:
# Echo the contents of a text file f = open('foo.txt', 'rt', encoding='utf-8') for line in f: ## iterates over the lines of the file print(line, end='') ## end='' so print does not add an end-of-line char ## since 'line' already includes the end-of-line. f.close()
一次阅读一行内容可以带来不错的效果,并非所有文件需要同时容纳在内存中;如果您想在不占用 10 GB 内存的情况下查看 10 GB 文件中的每一行,这会非常方便。f.readlines() 方法将整个文件读入内存中,并将其内容作为行列表返回。f.read() 方法会将整个文件读取到单个字符串中,这是一种一次性处理所有文本的便捷方式,例如使用稍后将看到的正则表达式。
在写入时,f.write(string) 方法是将数据写入开放输出文件的最简单方法。或者,您可以对打开的文件使用“print”,例如“print(string, file=f)”。
文件 Unicode
如需读取和写入 Unicode 编码文件,请使用“'t”模式并明确指定编码:
with open('foo.txt', 'rt', encoding='utf-8') as f: for line in f: # here line is a *unicode* string with open('write_test', encoding='utf-8', mode='wt') as f: f.write('\u20ACunicode\u20AC\n') # €unicode€ # AKA print('\u20ACunicode\u20AC', file=f) ## which auto-adds end='\n'
锻炼增量开发
构建 Python 程序时,无需一步即可编写整个代码。而应仅确定第一个里程碑,例如“第一步是提取字词列表”。编写代码以获得该里程碑,并在该时间点仅输出数据结构,然后您可以执行 sys.exit(0),使程序不会提前运行到未完成的部分。里程碑代码正常运行后,您便可以为下一个里程碑编写代码。若能查看变量在一种状态下的输出,将有助于思考如何转换这些变量以变为另一种状态。Python 在使用此模式时速度会很快,因此您可以稍作更改并运行程序,看看它的工作原理。利用如此快速的周转时间,只需几步即可构建您的计划。
练习:wordcount.py
结合所有基本的 Python 资料(字符串、列表、字典、元组、文件),尝试基本练习中的摘要 wordcount.py 练习。