Learning.Python.3rd.Edition 笔记[7:8]

Chapter 8
Lists and Dictionaries
链表与字典

List是可以同时包含任意的类型对象的集合,可以使用索引进行访问的有序集合,同时可以任意修改
所包含的内容

常见的List方法

L1 = [] An empty list
L2 = [0, 1, 2, 3] Four items: indexes 0..3
L3 = ['abc', ['def', 'ghi']] Nested sublists
L2[i] Index, index of index, slice, length
L3[i][j]
L2[i:j]
len(L2)
L1 + L2 Concatenate, repeat
L2 * 3
for x in L2 Iteration, membership
3 in L2
L2.append(4) Methods: grow, sort, search, insert, reverse, etc.
L2.extend([5,6,7])
L2.sort( )
L2.index(1)
L2.insert(I, X)
L2.reverse( )
del L2[k] Shrinking
del L2[i:j]
L2.pop( )
L2.remove(2)
L2[i:j] = []
L2[i] = 1 Index assignment, slice assignment
L2[i:j] = [4,5,6]
range(4) Make lists/tuples of integers
xrange(0, 4)
L4 = [x**2 for x in range(5)] List comprehensions (Chapters 13 and 17)

详细介绍
List 提供了和String一样的 +和*操作,concatenation and repetition
需要注意:不能将List与str直接相+,可以先使用List(str)进行转换

在使用append()方法时,返回将会返回一个None类型,应为list本身是可修改的,所以append将会影响到本身,
所以不需要和string一样的操作

del 可以用于删除List的切片或者单个元素,调用与方法并不相同

Dictionaries 字典

在Python内建数据类型中功能最为灵活,相对与List,可以理解成是无序的,如同其他语言一样 key:value的方式

使用key进行访问.而不使用索引,类型为dict,如:dir(dict)

常见的方法与操作
D1 = {} Empty dictionary
D2 = {'spam': 2, 'eggs': 3} Two-item dictionary
D3 = {'food': {'ham': 1, 'egg': 2}} Nesting
D2['eggs'] Indexing by key
D3['food']['ham']
D2.has_key('eggs') Methods: membership test, keys list, values list, copies,
'eggs' in D2 defaults, merge, delete, etc.
D2.keys( )
D2.values( )
D2.copy( )
D2.get(key, default)
D2.update(D1)
D2.pop(key)
len(D1) Length (number of stored entries)
D2[key] = 42 Adding/changing keys, deleting keys
del D2[key]
D4 = dict.fromvalues(['a', 'b']) Alternative construction techniques
D5 = dict(zip(keyslist, valslist))
D6 = dict(name='Bob', age=42)


d2.get('toast', 88) 用于在字典中取值时,88为key不存在时的默认值
d2.update(d3) 可以用批量更新字典,如果key不存在,则会自动添加
values() items() keys() 都会返回对应的list

可以通过循环keys()的方式,进行字典的遍历

字典中的key不一定都是str,可以使用元组和int作为key

在平常使用中,可以多注意使用.has_key()方法判断key是否存在

从list中创建dict字典的方式
dict([('name', 'mel'), ('age', 45)])

dict字典常用于存储数据,类似Json的格式,而且少了Java中的类型转换

批量创建dict字典的方式,并且赋予默认值
dict.fromkeys(['a', 'b'], 0)

凑字数问题(不过题目的确可以好好看看):

Chapter Quiz

1. Name two ways to build a list containing five integer zeros.

2. Name two ways to build a dictionary with two keys 'a' and 'b' each having an
associated value of 0.

3. Name four operations that change a list object in-place.

4. Name four operations that change a dictionary object in-place.

Quiz Answers
1. A literal expression like [0, 0, 0, 0, 0] and a repetition expression like [0] * 5
will each create a list of five zeros. In practice, you might also build one up with a
loop that starts with an empty list and appends 0 to it in each iteration: L.append(0).
A list comprehension ([0 for i in range(5)]) could work here too, but this is more
work than you need to do.

2. A literal expression such as {'a': 0, 'b': 0}, or a series of assignments like D =
[], D['a'] = 0, D['b'] = 0 would create the desired dictionary. You can also use
the newer and simpler-to-code dict(a=0, b=0) keyword form, or the more flexible
dict([('a', 0), ('b', 0)]) key/value sequences form. Or, because all the
keys are the same, you can use the special form dict.fromkeys(['a', 'b'], 0).

3. The append and extend methods grow a list in-place, the sort and reverse methods
order and reverse lists, the insert method inserts an item at an offset, the
remove and pop methods delete from a list by value and by position, the del statement
deletes an item or slice, and index and slice assignment statements replace
an item or entire section. Pick any four of these for the quiz.

4. Dictionaries are primarily changed by assignment to a new or existing key,
which creates or changes the key’s entry in the table. Also, the del statement
deletes a key’s entry, the dictionary update method merges one dictionary into
another in-place, and D.pop(key) removes a key and returns the value it had.
Dictionaries also have other, more exotic in-place change methods not listed in
this chapter, such as setdefault; see reference sources for more details.


Chapter 9
Tuples, Files, and Everything Else
元组,文件和其他

Tuples 元组,不可变的列表(,),尤其注意单元素元组声明时,一定需要,号.
与List一样,是有序的集合对象,可以包含任意对象,使用索引进行访问,包括切片

常见的使用

() An empty tuple
t1 = (0,) A one-item tuple (not an expression)
t2 = (0, 'Ni', 1.2, 3) A four-item tuple
t2 = 0, 'Ni', 1.2, 3 Another four-item tuple (same as prior line)
t3 = ('abc', ('def', 'ghi')) Nested tuples
t1[i] Index, index of index, slice, length
t3[i][j]
t1[i:j]
len(t1)
t1 + t2 Concatenate, repeat
t2 * 3
for x in t Iteration, membership
'spam' in t2

其中最简单的声明元组的方式为
a=1, //注意,号必须存在

如果要对tuple进行排序,需要先将其转化成list

对于tuple的不可变,也只是影响顶层的tuple,而不影响内部元素对象的修改,与Java类似的概念

Files 文件对象

内置的open()方法可以创建一个file对象

打开的处理模式包括(open的第二个参数)
r --只打开输入流
w --只打开输出流
a --表示附加在文件末尾
a+--同时打开输入输出
b --表示以二进制流的方式打开
默认模式为r

常见操作
output = open('/tmp/spam', 'w') Create output file ('w' means write)
input = open('data', 'r') Create input file ('r' means read)
input = open('data') Same as prior line ('r' is the default)
aString = input.read( ) Read entire file into a single string
aString = input.read(N) Read next N bytes (one or more) into a string
aString = input.readline( ) Read next line (including end-of-line marker) into a string
aList = input.readlines( ) Read entire file into list of line strings
output.write(aString) Write a string of bytes into file
output.writelines(aList) Write all line strings in a list into file
output.close( ) Manual close (done for you when file is collected)
outout.flush( ) Flush output buffer to disk without closing
anyFile.seek(N) Change file position to offset N for next operation

注意文件打开后需要进行close()

写入文件时,可以手动写入'\n' 来达到换行的效果

以二进制的格式获取文件内容
open('datafile.txt').read( )

rstrip( )方法,与普通的读取方法区别在于自动过滤掉\n

使用eval,配合字符串,将文件中的读取的字符串转换成Python对象
parts=['[1, 2, 3]', "{'a': 1, 'b': 2}\n"]
objects = [eval(P) for P in parts]
objects==[[1, 2, 3], {'a': 1, 'b': 2}]

使用pickle,在文件中保存Python对象
使用eval转换字符串为对象,功能过于强大,有可能导致无法处理的危险性(如删除电脑上所有的文件)

pickle模块需要import,使用例子如下
import pickle
F = open('datafile.txt', 'w')
pickle.dump(D, F) //写入文件
F.close( )

打开文件后,使用pickle.load(F)进行读取

手动以流的形式保存信息到文件中, 使用struct模块

>>> F = open('data.bin', 'wb') # Open binary output file //注意打开的模式 w b
>>> import struct
>>> bytes = struct.pack('>i4sh', 7, 'spam', 8) //转换成指定格式的二进制流格式
>>> bytes
'\x00\x00\x00\x07spam\x00\x08' //生成的格式
>>> F.write(bytes)
>>> F.close( )

读取的方式

>>> F = open('data.bin', 'rb') //注意rb
>>> data = F.read( ) # Get packed binary data
>>> data
'\x00\x00\x00\x07spam\x00\x08'
>>> values = struct.unpack('>i4sh', data) # Convert to Python objects
>>> values
(7, 'spam', 8)


使用[:]拷贝一个list的时候,只会拷贝其中对象的引用,并不会创建新的对象

The == operator tests value equivalence ==用于判断对象值是否相同

The is operator tests object identity is用于判断对象是否为同一个


Python会自动缓存比较短的字符串,所以对两个相同内容字符串使用is时,将会为true,如果字符串
较长,将会返回false

Python将所有空的元素和0(包括浮点)判断为false,所有其他非空的数据元素为true

详细的例子列表
Object Value
"spam" True
"" False
[] False
{} False
1 True
0.0 False
None False

1:数字非0,即为true
2:对象非空(包括容器 所包含元素),即为true
3:None 为false

类型的判断方法,isinstance(obj,type)方法
isinstance([1],list)

如果出来环形数据结构,如果一个list内添加了一个自己的引用,Python将会使用[...]进行显示
>>> L = ['grail'] # Append reference to same object
>>> L.append(L) # Generates cycle in object: [...]
>>> L
['grail', [...]]

本章的问题较多,可以自行找PDF查看
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值