VectorLu

《Python 学习手册》笔记

Python 初学者的困惑之一就是——我应该学习 Python2 还是 Python3,听上去很可笑,但是的确如此——身边真的有同学因为 Python 有长期支持的两个版本而不知所措……

当然是学习 Python3,但是也需要了解 Python2——去阅读一些历史遗留代码。其实这两者的区别并不大,学会了 Python3,只需要注意一些细节或者在需要时查看一下相关文档就很快能上手 Python2 的代码。

这本书实在是啰嗦而非详细,不推荐这本书。

动物出版社的《Python 学习手册》并不是一本广受推荐的 Python 学习书籍——因为它介绍了 Python2/3 中的不同,并将 Python 与许多其他编程语言比较,显得过于啰嗦,中文版有一千多页。不过如果有编程基础,其实能浏览得很快,比较集中地获取到 Python 文档中不够集中详尽的基础知识。

介绍 Python 对象类型

Python 中各种类型的简介。

Python 是动态类型——它自动跟踪变量类型而不要求声明类型(实际上,如果你像大多数的语言中 int i = 0 专门声明变量的语言,Python 会报错)。但 Python 也是强类型语言——只能对一个对象进行适合该类型的有效的操作。一旦创建了一个对象,它就和操作集合绑定了。

数字

math 模块中包含一些常用的数学工具

1
2
3
4
5
6
7
>>> import math
>>> math.pi
3.141592653589793
>>> math.sqrt(81)
9.0
>>> math.sqrt(7)
2.6457513110645907

random 模块可以作为随机数字的生成器和随机选择器(从 Python 列表中选择)

1
2
3
4
5
>>> import random
>>> random.random()
0.34685948620203444
>>> random.choice([1, 2, 3, 4])
2

访问序列时,负的索引号会简单地与长度相加——就是这样实现逆序访问的。

字符串

1
2
3
4
5
6
>>> S = 'spam'
>>> S.find('pa') # Find the offset of a substring
1
>>> S = 'spams'
>>> S.replace('s', 'XYZ') # Replace occurrences of a substring with another
'XYZpamXYZ'

从 Python2.6 和 Python3.0 开始支持格式化的高级替换操作:

1
2
3
4
5
6
>>> '%s, eggs, and %s' % ('spam', 'SPAM!') # Formatting expre
ssion(all)
'spam, eggs, and SPAM!'
>>> '{0}, eggs, and {1}'.format('spam', 'SPAM!') # Formatting
method(2.6, 3.0)
'spam, eggs, and SPAM!'

寻求帮助

可用作多种类型的通用型操作都是以内置函数存在,例如 Python3 内置函数。但是类型特定的操作是以方法调用的形式出现的,例如 aString.upper()

help()dir() 是寻求帮助的好方法。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
>>> aString = 'string'
>>> help(aString.replace)
Help on built-in function replace:
replace(...) method of builtins.str instance
S.replace(old, new[, count]) -> str
Return a copy of S with all occurrences of substring
old replaced by new. If the optional argument count is
given, only the first count occurrences are replaced.
>>> dir(aString)
['__add__', '__class__', '__contains__', '__delattr__', '__dir__
', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute_
_', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__in
it__', '__init_subclass__', '__iter__', '__le__', '__len__', '__
lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__',
'__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr_
_', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', '
casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs'
, 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha',
'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric',
'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust'
, 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind
', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split',
'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'tran
slate', 'upper', 'zfill']

列表解析式

实际中的列表解析式可能会更复杂。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
>>> M = [
... [1, 2, 3],
... [4, 5, 6],
... [7, 8, 9]]
>>> M
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
>>> [row[1] + 1 for row in M]
[3, 6, 9]
>>> [row[1] for row in M if row[1]%2==0] # Filter out odd items
[2, 8]
>>> diag = [M[i][i] for i in [0, 1, 2]] # Collect a diagonal fro
m matrix
>>> diag
[1, 5, 9]
>>> doubles = [c * 2 for c in 'spam']
>>> doubles
['ss', 'pp', 'aa', 'mm']

在 Python3.0 之后,列表、集合、字典都可以用解析创建。

1
2
3
4
5
6
>>> [ord(x) for x in 'spaam'] # List of character ordinals
[115, 112, 97, 97, 109]
>>> {ord(x) for x in 'spaam'} # Sets remove duplicates
{112, 97, 115, 109}
>>> {x: ord(x) for x in 'spam'} # Dictionary keys are unique
{'s': 115, 'p': 112, 'a': 97, 'm': 109}

列表解析和相关函数工具,如 mapfilter,通常运行得比 for 循环快。

数字

random 模块十分重要。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
>>> import random
>>> random.random()
0.27638963452049203
>>> random.random()
0.5354660732169736
>>> random.randint()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: randint() missing 2 required positional arguments: 'a
' and 'b'
>>> random.randint(1, 11)
2
>>> random.randint(1, 11)
4
>>> random.choice(['Life of Brian', 'Holy Grail', 'Meaning of Li
fe'])
'Holy Grail'
>>> random.choice(['Life of Brian', 'Holy Grail', 'Meaning of Li
fe'])
'Life of Brian'
>>> random.choice(['Life of Brian', 'Holy Grail', 'Meaning of Li
fe'])
'Life of Brian'
>>> random.choice(['Life of Brian', 'Holy Grail', 'Meaning of Li
fe'])
'Holy Grail'
>>> random.choice(['Life of Brian', 'Holy Grail', 'Meaning of Li
fe'])
'Meaning of Life'

设置全局精度

decimal 对于货币运算的应用程序十分重要。

设置全局的默认精度:

1
2
3
4
5
6
7
8
9
10
11
>>> import decimal
>>> decimal.Decimal(1) / decimal.Decimal(7)
Decimal('0.1428571428571428571428571429')
>>> decimal.getcontext().prec = 4
>>> decimal.Decimal(1) / decimal.Decimal(7)
Decimal('0.1429')
>>> pay = decimal.Decimal(str(1999+1.33333))
>>> pay
Decimal('2000.33333')
>>> decimal.Decimal(1) / decimal.Decimal(3)
Decimal('0.3333')

设置临时精度

1
2
3
4
5
6
7
8
9
10
11
12
13
>>> import decimal
>>> decimal.Decimal(1) / decimal.Decimal(3)
Decimal('0.3333333333333333333333333333')
>>>
>>> with decimal.localcontext() as ctx:
... ctx.prec = 2
... decimal.Decimal('1.00') / decimal.Decimal('3.00')
...
Decimal('0.33')
>>>
>>> decimal.Decimal(1) / decimal.Decimal(3)
Decimal('0.3333333333333333333333333333')

分数类型

明确地保留了一个分子和一个分母,从而避免了了浮点数字的不精确性。分数对象也可以从浮点字符串来创建。分数保持精确性,并自动简化结果。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
>>> from fractions import Fraction
>>> x = Fraction(1, 3)
>>> y = Fraction(4, 6)
>>> y
Fraction(2, 3)
>>> print(y)
2/3
>>> x + y
Fraction(1, 1)
>>> Fraction('.25')
Fraction(1, 4)
>>> Fraction('.25') + Fraction('1.25')
Fraction(3, 2)

集合

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
>>> x = set('abcde')
>>> y = set('bdxyz')
>>> x
{'b', 'a', 'c', 'e', 'd'}
>>> 'e' in x
True
>>> x - y
{'a', 'e', 'c'}
>>> x | y # Union
{'b', 'x', 'a', 'y', 'c', 'z', 'e', 'd'}
>>> x & y # Intersection
{'b', 'd'}
>>> x ^ y # XOR
{'x', 'a', 'y', 'c', 'z', 'e'}
>>> x > y, x < y # Superset, subset
(False, False)

除了表达式,Python 还提供了相应的方法。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
>>> z = x.intersection(y) # Same as x & y
>>> z
{'b', 'd'}
>>> z.add('SPAM') # Insert one item
>>> z
{'SPAM', 'b', 'd'}
>>> z.update(set(['X', 'Y']) # Merge: in-place union
... z.update(set(['X', 'Y'])^C # Merge: in-place union
KeyboardInterrupt
>>> z.update(set(['X', 'Y'])) # Merge: in-place union
>>> z
{'SPAM', 'b', 'X', 'Y', 'd'}
>>> z.remove('b')
>>> z
{'SPAM', 'X', 'Y', 'd'}
>>> S = set([1, 2, 3])
>>> S | set([3, 4])
{1, 2, 3, 4}
>>> S | [3, 4]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for |: 'set' and 'list'
>>> S.union([3, 4])
{1, 2, 3, 4}
>>> S.intersection((1, 3, 5))
{1, 3}
>>> S.issubset(range(-5, 5))
True
>>> set('spam')
{'a', 's', 'p', 'm'}

注意,在 Python 中,{} 仍然是一个字典。空的集合必须通过内置函数 set() 创建。

1
2
3
4
5
6
7
8
>>> type({})
<class 'dict'>
>>> S = set() # Initialize an empty set
>>> S
set()
>>> S.add(1.23)
>>> S
{1.23}

集合只能包含不可变的(可散列的)对象类型。因此,列表和字典是不可以嵌入集合的,元组则可以,但是如果元组中嵌套了列表这种可变的对象类型,则不可以。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
>>> S.add([1, 2, 3])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'
>>> S.add({'a':1})
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'dict'
>>> S.add((1, 2, 3))
>>> S
{1.23, (1, 2, 3)}
>>> t = ([1, 3], 2, 3)
>>> t
([1, 3], 2, 3)
>>> S.add(t)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'

一些较为实际的例子:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
>>> engineers = {'bob', 'sue', 'ann', 'vic'}
>>> managers = {'tom', 'sue'}
>>> 'bob' in engineers
True
>>> engineers & managers
{'sue'}
>>> engineers | managers
{'ann', 'tom', 'bob', 'vic', 'sue'}
>>> engineers - managers
{'ann', 'vic', 'bob'}
>>> managers - engineers
{'tom'}
>>> engineers > managers # Are all managers engineers?
False
>>> managers > engineers # Are all engineers managers?
False
>>> {'bob', 'sue'} < engineers # Are both engineers?(subset)
True
>>> (managers | engineers) > managers # All people is a superset of managers
True
>>> managers ^ engineers # Who is in one but not both?
{'tom', 'bob', 'ann', 'vic'}

动态类型简介

Python 中的类型是和对象相关联的,而不是和变量相关联的。

字符串

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
>>> ord('s')
115
>>> chr(115)
's'
>>> B = '1101'
>>> I = 0
>>> while B != '':
... I = I * 2 + (ord(B[0]) - ord('0'))
... B = B[1:]
...
>>> I
13
>>> int('1101', 2)
13
>>> bin(13)
'0b1101'

replace() 方法实际上产生了一个新的字符串对象。如果需要对一个很长的字符串多处进行修改,为了优化脚本的性能,将字符串转换成支持原地修改的对象,比如列表,再用 ''.join(L) 一次性连接字符。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
>>> S = 'spammy'
>>> L = list(S)
>>> L
['s', 'p', 'a', 'm', 'm', 'y']
>>> L(3) = 'x'
File "<stdin>", line 1
SyntaxError: can't assign to function call
>>> L[3] = 'x'
>>> L[4] = 'x'
>>> L
['s', 'p', 'a', 'x', 'x', 'y']
>>> S = ''.join(L)
>>> S
'spaxxy'

格式化字符串

转换目标的通用结构:

1
%[(name)][flags][width][.precision]typecode

实例:

1
2
3
4
5
>>> x = 1.23456789
>>> x
1.23456789
>>> '%e | %f | %g' % (x, x, x)
'1.234568e+00 | 1.234568 | 1.23457'

如果再运行时,才知道大小,可以用 * 来制定通过计算得出 widthprecision,比如这里的 4 即为指定的精度:

1
2
>>> '%f, %.2f, %.*f' % (1/3.0, 1/3.0, 4, 1/3.0)
'0.333333, 0.33, 0.3333'

基于字典的字符串格式化

生成 HTML 或 XML 的程序中经常用到这一技巧。

1
2
3
4
5
6
7
8
9
10
11
>>> reply = '''
... Greeting...
... Hello %(name)s!
... Your age squared is %(age)s
... '''
>>> values = {'name': 'Bob', 'age': 40}
>>> print(reply % values)
Greeting...
Hello Bob!
Your age squared is 40

这样的技巧也经常配合内置函数 vars() 使用,该函数返回的字典包含了所有在本函数调用时存在的所有变量:

1
2
3
4
5
6
>>> food = 'spam'
>>> age = 40
>>> vars()
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, 'food': 'spam', 'age': 40}
>>> '%(age)d %(food)s' % vars()
'40 spam'

字符串格式化调用方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
>>> template = '{0}, {1} and {2}' # By position
>>> template.format('spam', 'ham', 'eggs')
'spam, ham and eggs'
>>> template = '{motto}, {pork} and {food}' # By keyword
>>> template.format(motto='spam', pork='ham', food='eggs')
'spam, ham and eggs'
>>> template = '{motto}, {0}, and {food}' # By both
>>> template.format('ham', motto='spam', food='eggs')
'spam, ham, and eggs'
>>> import sys
>>> 'My {1[spam]} runs {0.platform}'.format(sys, {'spam': 'laptop'})
'My laptop runs darwin'
>>> 'My {config[spam]} runs {sys.platform}'.format(sys=sys, config={'spam': 'laptop'})
'My laptop runs darwin'

列表

列表解析式

map() 函数有类似的功能,但它对序列中的各项应用一个函数,并把结果放在一个新列表中。

1
2
>>> list(map(abs, [-1, -2, 0, 1, 2]))
[1, 2, 0, 1, 2]

索引和分片的赋值

均为原地修改,没有生成新的列表。

列表方法调用

L.append(x) 是将单个元素加到列表的最后,原地修改。L+[X] 是将后一个列表合并到第一个列表中,生成一个新列表。

sort() 原地排序,返回值为 None

1
2
3
4
5
6
7
8
9
10
11
12
>>> L = ['abc', 'ABD', 'aBe']
>>> L.sort() # Sort with mixed case
>>> L
['ABD', 'aBe', 'abc']
>>> L = ['abc', 'ABD', 'aBe']
>>> L.sort(key = str.lower) # Normalize to lowercase
>>> L
['abc', 'ABD', 'aBe']
>>> L = ['abc', 'ABD', 'aBe']
>>> L.sort(key = str.lower, reverse = True) # Change sort order
>>> L
['aBe', 'ABD', 'abc']

有返回值的排序函数 sorted(),可以排序任意 collection

1
2
3
4
5
6
7
>>> L = ['abc', 'ABD', 'aBe']
>>> sorted(L, key=str.lower, reverse = True)
['aBe', 'ABD', 'abc']
>>> L
['abc', 'ABD', 'aBe']
>>> sorted([x.lower() for x in L], reverse=True)
['abe', 'abd', 'abc']

reverse() 可以原地反转列表,reversed() 可以像 sorted() 一样工作,但是必须包装在一个 list() 调用中,因为它是一个迭代器。

1
2
3
4
5
6
>>> L = [1, 2, 3, 4]
>>> L.reverse()
>>> L
[4, 3, 2, 1]
>>> list(reversed(L))
[1, 2, 3, 4]

字典

对于 pop() 方法,列表是根据位置返回值,而字典根据键来返回。get() 方法是最简洁的防止键不存在而导致异常的方法。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
>>> D = {'spam': 2, 'ham': 1, 'eggs': 3}
>>> list(D.values())
[2, 1, 3]
>>> list(D.items())
[('spam', 2), ('ham', 1), ('eggs', 3)]
>>> D.get('spam')
2
>>> print(D.get('toast'))
None
>>> D.get('toast', 88)
88
>>> D
{'spam': 2, 'ham': 1, 'eggs': 3}
>>> D2 = {'toast': 4, 'muffin': 5}
>>> D.update(D2)
>>> D
{'spam': 2, 'ham': 1, 'eggs': 3, 'toast': 4, 'muffin': 5}
>>> D.pop('muffin')
5
>>> D.pop('toast')
4
>>> D
{'spam': 2, 'ham': 1, 'eggs': 3}

字典用于稀疏数据结构

1
2
3
4
5
6
7
8
9
>>> Matrix = {}
>>> Matrix[(2, 3, 4)] = 88
>>> Matrix[(7, 8, 9)] = 99
>>>
>>> X = 2; Y = 3; Z = 4 # ; separate statements
>>> Matrix[(X, Y, Z)]
88
>>> Matrix
{(2, 3, 4): 88, (7, 8, 9): 99}

字典解析

zip() 函数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
>>> list(zip(['a', 'b', 'c'], [1, 2, 3])) # Zip together keys and values
[('a', 1), ('b', 2), ('c', 3)]
>>> D = dict(zip(['a', 'b', 'c'], [1, 2, 3])) # Make a dict from zip result
>>> D
{'a': 1, 'b': 2, 'c': 3}
>>> D = {x: x**2 for x in range(1, 5)} # dict comprehesions
>>> D
{1: 1, 2: 4, 3: 9, 4: 16}
>>> D = {c.lower(): c + '!' for c in ['SPAM', 'EGGS', 'HAM']}
>>> D
{'spam': 'SPAM!', 'eggs': 'EGGS!', 'ham': 'HAM!'}
>>> D = dict.fromkeys(['a', 'b', 'c'], 0) # Initialize dict from keys
>>> D
{'a': 0, 'b': 0, 'c': 0}
>>> D = {k:0 for k in ['a', 'b', 'c']} # Same, but with a comprehension
>>> D
{'a': 0, 'b': 0, 'c': 0}

字典视图

由于字典的键(字典的值不是)是不可变且唯一的,类似于集合,且支持集合的交并补等常见操作:

1
2
3
4
5
6
>>> D = {'a': 1, 'b': 2, 'c': 3}
>>> K = D.keys()
>>> K
dict_keys(['a', 'b', 'c'])
>>> K | {'x': 4} # Keys(and some items) views are set-like
{'x', 'c', 'a', 'b'}

元组、文件及其他

概览

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
>>> type(())
<class 'tuple'>
>>> T = (0,) # 单个元素的元组(非表达式)
>>> T
(0,)
>>> T = (0, 'Ni', 1.2, 3)
>>> T
(0, 'Ni', 1.2, 3)
>>> T1 = 0, 'Ni', 1.2, 3
>>> T1
(0, 'Ni', 1.2, 3)
>>> T = tuple('spam') # 一个可迭代对象的项的元组
>>> T
('s', 'p', 'a', 'm')
>>> T[1]
'p'
>>> T[0:]
('s', 'p', 'a', 'm')
>>> len(T)
4
>>> T + T1
('s', 'p', 'a', 'm', 0, 'Ni', 1.2, 3)
>>> T * 3
('s', 'p', 'a', 'm', 's', 'p', 'a', 'm', 's', 'p', 'a', 'm')
>>> 'spam' in T
False
>>> [x * 2 for x in T]
['ss', 'pp', 'aa', 'mm']
>>> T1.index('Ni')
1
>>> T1.count('Ni')
1

元组的特殊语法:逗号和圆括号

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
>>> x = (40)
>>> type(x)
<class 'int'>
>>> x = (40, )
>>> type(x)
<class 'tuple'>
>>> T = (1, 2, 3, 4, 5)
>>> L = [x + 20 for x in T]
>>> L
[21, 22, 23, 24, 25]
>>> L.index(23)
2
>>> T.count(21)
0

元组的不可变性只适合元组本身顶层,而非其内容。元组内部的列表是可以修改的。

文件

如果想要一行一行地扫描一个文件,文本迭代器往往是最好的选择。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
>>> myfile = open('myfile.txt', 'w')
>>> myfile.write('hello text file\n')
16
>>> myfile.write('goodbye text file\n')
18
>>> myfile.close()
>>> myfile = open('myfile.txt')
>>> myfile.readline()
'hello text file\n'
>>> myfile.readline()
'goodbye text file\n'
>>> myfile.readline()
''
>>> myfile.close()
>>> open('myfile.txt').read() # Read all at once into string
'hello text file\ngoodbye text file\n'
# 文本迭代器
>>> for line in open('myfile.txt'):
... print(line, end = '')
...
hello text file
goodbye text file

用工具将文件中字符串转换成 Python 中的对象

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
>>> x, y, z = 43, 44, 45
>>> S = 'Spam'
>>> D = {'a': 1, 'b': 2}
>>> L = [1, 2, 3]
>>> F = open('datafile.txt', 'w') # Create output file
>>> F.write(S + '\n') # Terminate lines with \n
5
>>> F.write('%s,%s,%s\n' % (x, y, z)) # Convert numbers to strings
9
>>> F.write(str(L) + '$' + str(D) + '\n') # Convert and separate with $
27
>>> F.close()
>>> chars = open('datafile.txt').read() # Raw string display
>>> chars
"Spam\n43,44,45\n[1, 2, 3]${'a': 1, 'b': 2}\n"
>>> print(chars) # User-friendly display
Spam
43,44,45
[1, 2, 3]${'a': 1, 'b': 2}

把文本中的字符串转换成 Python 中的对象:

对第一行的字符串,只需要用 rstrip() 去掉多余的行终止符即可,line[:-1] 也可以,但是要确定每一行最后都有 \n(可能最后一行没有 \n)。对于第二行的数字,用索引、分片和类型转换函数(会忽略数字旁边的空白)。对于最后一行,用强大的 eval() 函数,它会将参数当成 Python 语句来执行,返回执行结果。只要有相应权限,这一方法甚至能删除计算机上的所有文件。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
>>> F = open('datafile.txt')
>>> line = F.readline()
>>> line
'Spam\n'
>>> line.rstrip()
'Spam'
>>> line = F.readline()
>>> line
'43,44,45\n'
>>> parts = line.split(',') # Split(parse) on commas
>>> parts
['43', '44', '45\n']
>>> int(parts[1])
44
>>> numbers = [int(P) for P in parts] # Convert all in list at once
>>> numbers
[43, 44, 45]
>>> line = F.readline()
>>> line
"[1, 2, 3]${'a': 1, 'b': 2}\n"
>>> parts = line.split('$')
>>> parts
['[1, 2, 3]', "{'a': 1, 'b': 2}\n"]
>>> eval(parts[0])
[1, 2, 3]
>>> objects = [eval(P) for P in parts]
>>> objects
[[1, 2, 3], {'a': 1, 'b': 2}]

用 pickle 存储 Python 的原生对象

您的支持将鼓励我继续创作!

热评文章