'''代码源于书中例子,直接上码'''
import sys
from fractions import Fraction
from decimal import Decimal as D # rename for brevity
from operator import itemgetter
from collections import namedtuple
from collections import defaultdict
from collections import ChainMap
''''Integers使用'''
a = 12
b =3
print(a+b) # 相加 15
print(b-a) # 相减 -9
print(a//b) # 整除 4
print(a/b) # 真除 4.0
print(a*b) # 相乘 36
print(b**a) # 幂操作 531441
print(2**1024) # 幂操作 python可以处理非常大的数值操作
#true division (/) integer division (//)
print(7/4)
print(7//4)
print(-7/4)
print(-7//4)
print(10%3)#等价于10//3的余数
print(10%4)#等价于10//4的余数
'''Booleans使用'''
int(True) # True behaves like 1
int(False)#False behaves like 0
bool(1) #1 evaluates to True in a boolean context
bool(-42) # and so does every non-zero number
bool(0) # 0 evaluates to False
not True #False
not False #True
True and True #True
False or True #True
1 + True #2
False + 42 #42
7 - True # 6
'''Reals 实数的使用'''
pi = 3.1415926536 # how many digits of PI can you remember?
radius = 4.5
area = pi * (radius ** 2)
print(area)
print(sys.float_info)
print(3 * 0.1-0.3)# this should be 0!!! but answer is:5.551115123125783e-17
'''Complex numbers复数的使用'''
c = 3.14 + 2.73j
c.real # real part实数部分
c.imag # imaginary part虚数部分
c.conjugate() # conjugate of A + Bj is A - Bj
c * 2 # multiplication is allowed
c ** 2 # power operation as well
d = 1 + 1j # addition and subtraction as well
c - d
'''Fractions and decimals 分数和小数的使用'''
Fraction(10, 6) # mad hatter?
Fraction(1, 3) + Fraction(2, 3) # 1/3 + 2/3 = 3/3 = 1/1
f = Fraction(10, 6)
f.numerator #分子
f.denominator#分母
D(3.14) # pi, from float, so approximation issues
D('3.14') # pi, from a string, so no approximation issues(近似法问题)
D(0.1) * D(3) - D(0.3) # from float, we still have the issue
D('0.1') * D(3) - D('0.3') # from string, all perfect
'''Strings and bytes'''
# 4 ways to make a string
str1 = 'This is a string. We built it with single quotes.'
str2 = "This is also a string, but built with double quotes."
str3 = '''This is built using triple quotes,... so it can span multiple lines.'''
str4 = """This too... is a multiline one... built with triple double-quotes."""
len(str1)
#Encoding and decoding strings
s = "This is üŋíc0de" # unicode string: code points
encoded_s = s.encode('utf-8') # utf-8 encoded version of s
encoded_s.decode('utf-8') # let's revert to the original
'''Indexing and slicing strings'''
s = "The trouble is you think you have time."
s[0] # indexing at position 0, which is the first char:'T'
s[5] # indexing at position 5, which is the sixth char :'r'
s[:4] # slicing, we specify only the stop position: 'The '
s[4:] # slicing, we specify only the start position : 'trouble is you think you have time.'
s[2:14] # slicing, both start and stop positions :'e trouble is'
s[2:14:3] # slicing, start, stop and step (every 3 chars) : 'erb '
s[:] # quick way of making a copy : 'The trouble is you think you have time.'
'''Tuples元组的使用'''
t = () # empty tuple
type(t)
one_element_tuple = (42, ) # you need the comma!
three_elements_tuple = (1, 3, 5)
a, b, c = 1, 2, 3 # tuple for multiple assignment
a, b, c # implicit tuple to print with one instruction
print(3 in three_elements_tuple) # membership test
a, b = 1, 2
c = a # we need three lines and a temporary var c
a = b
b = c
a, b # a and b have been swapped
#another way
a, b = b, a # this is the Pythonic way to do it(swapped)
'''Lists使用'''
[] # empty list
list() # same as []
[1, 2, 3] # as with tuples, items are comma separated
[x + 5 for x in [2, 3, 4]] # Python is magic :[7, 8, 9]
list((1, 3, 5, 7, 9)) # list from a tuple
list('hello') # list from a string:['h', 'e', 'l', 'l', 'o']
a = [1, 2, 1, 3]
a.append(13) # we can append anything at the end : [1, 2, 1, 3, 13]
a.count(1) # how many `1` are there in the list? 2
a.extend([5, 7]) #extend the list by another (or sequence) [1, 2, 1, 3, 13, 5, 7]
a.index(13) # position of `13` in the list (0-based indexing) 4
a.insert(0, 17) #insert `17` at position 0 [17, 1, 2, 1, 3, 13, 5, 7]
a.pop() # pop (remove and return) last element 7
a.pop(3) # pop element at position 3 :1
a.remove(17) # remove `17` from the list
a.reverse() # reverse the order of the elements in the list
a.sort() # sort the list
a.clear() # remove all elements from the list
a = list('hello') # makes a list from a string
a.append(100) # append 100, heterogeneous type
a.extend((1, 2, 3)) # extend using tuple
a.extend('...') # extend using string
a = [1, 3, 5, 7]
min(a) # minimum value in the list 1
max(a) #maximum value in the list
sum(a) #sum of all values in the list 16
len(a) # number of elements in the list
b=[6, 7, 8]
a + b # `+` with list means concatenation [1, 3, 5, 7, 6, 7, 8]
a * 2 # `*` has also a special meaning [1, 3, 5, 7, 1, 3, 5, 7]
a = [(5, 3), (1, 3), (1, 2), (2, -1), (4, 9)]
sorted(a)
sorted(a, key=itemgetter(0))
sorted(a, key=itemgetter(0, 1))
sorted(a, key=itemgetter(1))
sorted(a, key=itemgetter(1), reverse=True)
'''Byte arrays'''
bytearray() # empty bytearray object
bytearray(10)# zero-filled instance with given length bytearray(b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00')
bytearray(range(5)) # bytearray from iterable of integers bytearray(b'\x00\x01\x02\x03\x04')
name = bytearray(b'Lina') # A - bytearray from bytes
name.replace(b'L', b'l') #bytearray(b'lina')
name.endswith(b'na')#True
name.upper()
name.count(b'L')
'''Set'''
small_primes = set() # empty set
small_primes.add(2) # adding one element at a time
small_primes.add(3)
small_primes.add(5)
print(small_primes) # {2, 3, 5}
small_primes.add(1) # Look what I've done, 1 is not a prime! {1, 2, 3, 5}
small_primes.remove(1) # so let's remove it
print(3 in small_primes) # membership test
print(4 in small_primes)
print(4 not in small_primes)
small_primes.add(3) # trying to add 3 again; no change, duplication is not allowed
bigger_primes = set([5, 7, 11, 13]) # faster creation
small_primes | bigger_primes # union operator `|` {2, 3, 5, 7, 11, 13}
small_primes & bigger_primes # intersection operator `&` 取得交集 {5}
small_primes - bigger_primes # difference operator `-` {2, 3}
#immutable set :frozenset
small_primes = frozenset([2, 3, 5, 7])
bigger_primes = frozenset([5, 7, 11])
small_primes.add(11) # we cannot add to a frozenset
small_primes.remove(2) # neither we can remove
small_primes & bigger_primes # intersect, union, etc. allowed
'''dictionaries'''
a = dict(A=1, Z=-1)
b = {'A': 1, 'Z': -1}
c = dict(zip(['A', 'Z'], [1, -1]))
d = dict([('A', 1), ('Z', -1)])
e = dict({'Z': -1, 'A': 1})
print(a == b == c == d == e) # are they all the same?True # indeed!
list(zip(['h', 'e', 'l', 'l', 'o'], [1, 2, 3, 4, 5])) # [('h', 1), ('e', 2), ('l', 3), ('l', 4), ('o', 5)]
list(zip('hello', range(1, 6))) # equivalent, more Pythonic [('h', 1), ('e', 2), ('l', 3), ('l', 4), ('o', 5)]
d = {}
d['a'] = 1 # let's set a couple of (key, value) pairs
d['b'] = 2
len(d) # how many pairs?
d['a'] #what is the value of 'a'?
del d['a'] # let's remove `a`
d['c'] = 3 # let's add 'c': 3
print('c' in d) # membership is checked against the keys
print(3 in d) # not the values
d.clear()
d = dict(zip('hello', range(5))) #{'e': 1, 'h': 0, 'o': 4, 'l': 3}
d.keys() #dict_keys(['e', 'h', 'o', 'l'])
d.values()#dict_values([1, 0, 4, 3])
d.items()#dict_items([('e', 1), ('h', 0), ('o', 4), ('l', 3)])
print(3 in d.values())#True
print(('o', 4) in d.items())
d.popitem() # removes a random item
d.pop('l') # remove item with key `l`
d.pop('not-a-key') #remove a key not in dictionary: KeyError Traceback (most recent call last): File "", line 1, in KeyError: 'not-a-key'
d.pop('not-a-key', 'default-value') # with a default value?'default-value' # we get the default value
d.update({'another': 'value'}) # we can update dict this way
d.update(a=13) # or this way (like a function call)
d.get('a') # same as d['a'] but if key is missing no KeyError
d.get('a', 177) # default value used if key is missing
d = {}
d.setdefault('a', 1) # 'a' is missing, we get default value
d.setdefault('a', 5) # let's try to override the value
'''collections使用 '''
#namedtuple
Vision = namedtuple('Vision', ['left', 'right'])
vision = Vision(9.5, 8.8)
vision[0]
vision.left # same as vision[0], but explicit
vision.right # same as vision[1], but explicit
Vision = namedtuple('Vision', ['left', 'combined', 'right'])
vision = Vision(9.5, 9.2, 8.8)
vision.left # still perfect
vision.right # still perfect (though now is vision[2])
vision.combined # the new vision[1]
#Defaultdict
d = {}
d['age'] = d.get('age', 0) + 1 # age not there, we get 0 + 1
d = {'age': 39}
d['age'] = d.get('age', 0) + 1 # d is there, we get 40
dd = defaultdict(int) # int is the default type (0 the value)
dd['age'] += 1 # short for dd['age'] = dd['age'] + 1
dd['age'] = 39
dd['age'] += 1
#ChainMap
default_connection = {'host': 'localhost', 'port': 4567}
connection = {'port': 5678}
conn = ChainMap(connection, default_connection) # map creation
conn['port'] # port is found in the first dictionary 5678
conn['host'] # host is fetched from the second dictionary 'localhost'
conn.maps # we can see the mapping objects [{'port': 5678}, {'host': 'localhost', 'port': 4567}]
conn['host'] = 'packtpub.com' # let's add host
print(conn.maps)#[{'host': 'packtpub.com', 'port': 5678},{'host': 'localhost', 'port': 4567}]
del conn['port'] # let's remove the port information
dict(conn) # easy to merge and convert to regular dictionary
'''Small values caching 小的数值缓存'''
a = 1000000
b = 1000000
print(id(a) == id(b))# False
a = 5
b = 5
print(id(a) == id(b))# True Oh oh! Is Python broken? 哈哈