Storing native Python objects with pickle
If you really want to store native Python objects,but you ;can't trust the source of
the data in the file,Python's standard library pickle module is ideal.
查看Python 3.0的帮助手册可以看到,格式化字符串的值在Python的类型是bytes类型。所以我们在
bytes类型前面加上一个b就可以解决这个问题了。
F=open('data.bin','wb')
import struct
data=struct.pack('>i4sh',7,b'spam',8)
0\x00\x07spam\x00\x08'
Type Categories Revisited
Objedts share operations according to their category
Only mutable objects(lists,dictionaried,and sets)may be changed in-place
Files export only methods,so mutability doesn't really apply to them
"Numbers" in Table9-3 includes all number types
Sets are something like the keys of a valueless dictionary,but they don't map to values
and are not ordered,so sets are neither a mapping nor a sequence type
The== operator tests value equivalence
The is operator tests object identity
几种基本数值类型练习
>>> 2/5,2/5.0
(0.4, 0.4)
>>> 'spam'+'eggs'
'spameggs'
>>> S='ham'
>>> 'eggs'+S
'eggsham'
'hamhamhamhamham'
''
>>> "green%s and %s"%('eggs',S)
'greeneggs and ham'
>>> 'greenand'.format('egge',S)
'greeneggeandham'
>>> ('x',)[0]
'x'
>>> ('x','y')[1]
'y'
>>> L=[1,2,3]+[4,5,6]
>>> L,L[:],L[:0],L[-2],L[-2:]
([1, 2, 3, 4, 5, 6], [1, 2, 3, 4, 5, 6], [], 5, [5, 6])
>>> ([1,2,3]+[4,5,6])[2:4]
[3, 4]
>>> [L[2],L[3]]
[3, 4]
>>> L.reverse();L
[6, 5, 4, 3, 2, 1]
>>> L.sort()
[1, 2, 3, 4, 5, 6]
>>> L.index(4)
3
>>> {'a':1,'b':2}['b']
2
>>> D={'x':1,'y':2,'z':3}
>>> D['w']=0
>>> D['x']+D['w']
1
>>> D[(1,2,3)]=4
{(1, 2, 3): 4, 'y': 2, 'w': 0, 'z': 3, 'x': 1}
>>> list(D.keys()),list(D.values()),(1,2,3)in D
([(1, 2, 3), 'y', 'w', 'z', 'x'], [4, 2, 0, 3, 1], True)
{(1, 2, 3): 4, 'y': 2, 'w': 0, 'z': 3, 'x': 1}
>>> [[]],["",[],(),{},None]
([[]], ['', [], (), {}, None])
Everything is a type of object in Python,even the type of an object!
the type of an object is an object of type type .
[4, 5, 6]
>>> Y=[L]*4
[4, 5, 6, 4, 5, 6, 4, 5, 6, 4, 5, 6]
[[4, 5, 6], [4, 5, 6], [4, 5, 6], [4, 5, 6]]
>>> L[1]=0
[4, 5, 6, 4, 5, 6, 4, 5, 6, 4, 5, 6]
[[4, 0, 6], [4, 0, 6], [4, 0, 6], [4, 0, 6]]
[4, 5, 6, 4, 5, 6, 4, 5, 6, 4, 5, 6]
repetition,concatenation,and slicing copy only the top level of their operand
objects,these sorts of cases make much more sense.
Pycharm 一种专门的Python开发工具,研究摸索中。
领取专属 10元无门槛券
私享最新 技术干货