Python3高级基础(1)

[TOC]

Introducing Python Object Types

对象类型的优势

  1. Built-in objects make programs easy to write
  2. Built-in objects are components of extensions
  3. Built-in objects are often more efficient than custom data structures
  4. Built-in objects are a standard part of the language

Python的核心数据类型

数字 = Number

123+222 #整数的加法
345
1.5 * 4 #浮点型的乘法
6.0
2**100 # 2的100次幂
1267650600228229401496703205376
len(str(2 ** 100))
31
3.1415*2
6.283
import math # 导入数学模块
print('$\pi$的数值是:{}'.format(math.pi))
print('85的开方是:{}'.format(math.sqrt(85)))
$\pi$的数值是:3.141592653589793
85的开方是:9.219544457292887
import random
random.random()
0.6182188298420788

字符串

  • 序列操作
S = 'bright'
print('S的长度是: {}'.format(len(S)))
print('第1个元素: {}'.format(S[0]))
print('第2个元素: {}'.format(S[1]))
print('第3个元素: {}'.format(S[2]))
print('第4个元素: {}'.format(S[3]))
print('第5个元素: {}'.format(S[4]))
print('第6个元素: {}'.format(S[5]))
print('最后1个元素第一种求法: {}'.format(S[-1]))
print('最后1个元素第二种求法: {}'.format(S[len(S)-1]))
print('倒数第2个元素: {}'.format(S[-2]))
S的长度是: 6
第1个元素: b
第2个元素: r
第3个元素: i
第4个元素: g
第5个元素: h
第6个元素: t
最后1个元素第一种求法: t
最后1个元素第二种求法: t
倒数第2个元素: h
# 切片操作
print('Slice of S from offsets 1 through 2 (not 3): {}'.format(S[1:3]))
print('Everything past the first (1:len(S)): {}'.format(S[1:]))
print('S itself hasn\'t changed: {}'.format(S))
print('Everything but the last: {}'.format(S[0:6]))
print('Everything but the last again, but simpler (0:-1): {}'.format(S[:-1]))
print('Same as S[0:6]: {}'.format(S[:6]))
print('All of S as a top-level copy (0:len(S)): {}'.format(S[:]))
Slice of S from offsets 1 through 2 (not 3): ri
Everything past the first (1:len(S)): right
S itself hasn't changed: bright
Everything but the last: bright
Everything but the last again, but simpler (0:-1): brigh
Same as S[0:6]: bright
All of S as a top-level copy (0:len(S)): bright
# 字符串的加法与乘法
S1 = 'I'
S2 = ' like'
S3 = ' you! '
print('字符串的加法运算: {}'.format(S1+S2+S3))
print('字符串的乘法运算: {}'.format((S1+S2+S3)*3))
字符串的加法运算: I like you! 
字符串的乘法运算: I like you! I like you! I like you! 
  • 字符串的不可变形 = immutability
Str1 = 'Yuxl'
print(Str1)
try:
    Str1[0] = 'XX'
except:
    print("不可更改")
Yuxl
不可更改
  • We can run expressions to make new objects
print('Str1原来的形式: {}'.format(Str1))
Str1 = 'XX' + Str1[1:]
print('Str1修改后的形式: {}'.format(Str1))
Str1原来的形式: Yuxl
Str1修改后的形式: XXuxl
  • 字符串的类型方法
S = 'Spam'
# S.find()
print('Find the offset of a substring: {}'.format(S.find('pa')))
# S.replace(S中有的字符,定义字符替换原字符)
print('Replace occurrences of a substring with another: {}'.format(S.replace('pa','XYZ')))
print('替换后原字符串不变: {}'.format(S))
Find the offset of a substring: 1
Replace occurrences of a substring with another: SXYZm
替换后源字符串不变: Spam
line = 'aaa,bbb,ccccc,dd'
print('Split on a delimiter into a list of substrings: {}'.format(line.split(',')))
line1 = 'aaa,bbb,ccccc,dd\n'
print('打印原line1: {}'.format(line1))
print('Remove whitespace characters on the right side: {}'.format(line.rstrip()))
print('打印操作后的line1: {}'.format(line1))
print('-----------------------')
Split on a delimiter into a list of substrings: ['aaa', 'bbb', 'ccccc', 'dd']
打印原line1: aaa,bbb,ccccc,dd

Remove whitespace characters on the right side: aaa,bbb,ccccc,dd
打印操作后的line1: aaa,bbb,ccccc,dd

-----------------------
S = 'Bright'
print('Upper- and lowercase conversions: {}'.format(S.upper()))
print('Content tests: isalpha, isdigit, etc.: {}'.format(S.isalpha()))
Upper- and lowercase conversions: BRIGHT
Content tests: isalpha, isdigit, etc.: True
S = 'A\nB\tC' # \n is end-of-line, \t is tab
print(S)
A
B   C
len(S) #Each stands for just one character
5
print('\\n is a byte with the binary value 10 in ASCII: {}'.format(ord('\n')))
\n is a byte with the binary value 10 in ASCII: 10
S = 'A\oB\oC'
print(S)
len(S)
A\oB\oC





7
msg = """ aaaaaaaaaaaaa
bbb'''bbbbbbbbbb""bbbbbbb'bbbb
cccccccccccccc"""
print(msg)
 aaaaaaaaaaaaa
bbb'''bbbbbbbbbb""bbbbbbb'bbbb
cccccccccccccc
msg
' aaaaaaaaaaaaa\nbbb\'\'\'bbbbbbbbbb""bbbbbbb\'bbbb\ncccccccccccccc'
  • 模式匹配 = Pattern Matching
import re
match = re.match('Hello[ \t]*(.*)world', 'Hello    Python world')
match.group(1)
'Python '
match = re.match('/(.*)/(.*)/(.*)', '/usr/home/lumberjack')
match.groups()
('usr', 'home', 'lumberjack')

列表 = lists

  • 序列操作
L = [123,'spam',1.23]
print('Number of items in the list: {}'.format(len(L)))
print('Indexing by position: {}'.format(L[0]))
print('Slicing a list returns a new list: {}'.format(L[:-1]))
print('Concatenation makes a new list too: {}'.format(L+[4,5,6]))
print('We\'re not changing the original list: {}'.format(L))
Number of items in the list: 3
Indexing by position: 123
Slicing a list returns a new list: [123, 'spam']
Concatenation makes a new list too: [123, 'spam', 1.23, 4, 5, 6]
We're not changing the original list: [123, 'spam', 1.23]
  • 类型方法操作
L = [123,'spam',1.23]
print('Growing: add object at end of list: {}, 列表{}'.format(L.append('NI'),L))
print('Shrinking: delete an item in the middle: {}'.format(L.pop(2)))
print('"del L[2]" deletes from a list too: {}'.format(L))
M = ['bb','aa','cc']
print('M排序: {},{}'.format(M.sort(),M))
print('M元素翻转: {},{}'.format(M.reverse(),M))
Growing: add object at end of list: None, 列表[123, 'spam', 1.23, 'NI']
Shrinking: delete an item in the middle: 1.23
"del L[2]" deletes from a list too: [123, 'spam', 'NI']
M排序: None,['aa', 'bb', 'cc']
M元素翻转: None,['cc', 'bb', 'aa']
  • 列表嵌套 = nesting
M = [[1,2,3],
    [4,5,6],
    [7,8,9]]
print(M)
print('第2行: {}'.format(M[1]))
print('Get row 2, then get item 3 within the row: {}'.format(M[1][2]))
# 列表解析
col2 = [row[1] for row in M]
print('Collect the items in column 2: {}'.format(col2))
print('The matrix is unchanged: {}'.format(M))
print('Add 1 to each item in column 2: {}'.format([row[1]+1 for row in M]))
print('Filter out odd items: {}'.format([row[1] for row in M if row[1]%2==0]))
print('打印矩阵M: {}'.format(M))
diag = [M[i][i] for i in [0,1,2]]
print('Collect a diagonal from matrix: {}'.format(diag))
print('Repeat characters in a string: {}'.format([c*2 for c in 'bright']))
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
第2行: [4, 5, 6]
Get row 2, then get item 3 within the row: 6
Collect the items in column 2: [2, 5, 8]
The matrix is unchanged: [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
Add 1 to each item in column 2: [3, 6, 9]
Filter out odd items: [2, 8]
打印矩阵M: [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
Collect a diagonal from matrix: [1, 5, 9]
Repeat characters in a string: ['bb', 'rr', 'ii', 'gg', 'hh', 'tt']
print('打印M: {}'.format(M))
G = (sum(row) for row in M)
print('Create a generator of row sums: {}'.format(next(G)))
print('Run the iteration protocol: {}'.format(next(G)))
打印M: [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
Create a generator of row sums: 6
Run the iteration protocol: 15
print('Map sum over items in M: {}'.format(list(map(sum,M))))
print('Create a set of row sums: {}'.format({sum(row)for row in M}))
print('Creates key/value table of row sums: {}'.format({i : sum(M[i]) for i in range(3)}))
print('List of character ordinals: {}'.format([ord(x) for x in 'spaam']))
print('Sets remove duplicates: {}'.format({ord(x) for x in 'spaam'}))
print('Dictionary keys are unique: {}'.format({x:ord(x) for x in 'spaam'}))
Map sum over items in M: [6, 15, 24]
Create a set of row sums: {24, 6, 15}
Creates key/value table of row sums: {0: 6, 1: 15, 2: 24}
List of character ordinals: [115, 112, 97, 97, 109]
Sets remove duplicates: {112, 97, 115, 109}
Dictionary keys are unique: {'s': 115, 'p': 112, 'a': 97, 'm': 109}

字典 = dictionary

  • 映射操作
D = {'food': 'Spam', 'quantity': 4, 'color': 'pink'}
print('Fetch value of key \'food\': {}'.format(D['food']))
print('Add 1 to \'quantity\' value: {},\n打印:{}'.format(D['quantity'] + 1 , D))
D = {}
# Create keys by assignment
D['Name']='bright'
D['Job']='student'
D['Style']='popular'
print('打印D: {}'.format(D))
print('打印D[\'name\']: {}'.format(D['Name']))
Fetch value of key 'food': Spam
Add 1 to 'quantity' value: 5,
打印:{'food': 'Spam', 'quantity': 4, 'color': 'pink'}
打印D: {'Name': 'bright', 'Job': 'student', 'Style': 'popular'}
打印D['name']: bright
  • 字典嵌套
rec = {'name': {'first': 'Bob', 'last': 'Smith'},
'job': ['dev', 'mgr'],
'age': 40.5}
print('打印rec的名字: {}'.format(rec['name']))
print('Index the nested dictionary: {}'.format(rec['name']['last']))
print('\'job\' is a nested list: {}'.format(rec['job']))
print('# Index the nested list: {}'.format(rec['job'][-1]))
print('Expand Bob\'s job description in-place: {}\n打印: {}'.
      format(rec['job'].append('janitor'),rec))
打印rec的名字: {'first': 'Bob', 'last': 'Smith'}
Index the nested dictionary: Smith
'job' is a nested list: ['dev', 'mgr']
# Index the nested list: mgr
Expand Bob's job description in-place: None
打印: {'name': {'first': 'Bob', 'last': 'Smith'}, 'job': ['dev', 'mgr', 'janitor'], 'age': 40.5}
  • 字典排序整理
D = {'a':1,'b':2,'c':3}
print('D: {}'.format(D))
print('Unordered keys list: {}'.format(list(D.keys())))
print('Sorted keys list: {}'.format((list(D.keys())).sort()))
for key in D.keys():
    print(key, '=>', D[key])
D: {'a': 1, 'b': 2, 'c': 3}
Unordered keys list: ['a', 'b', 'c']
Sorted keys list: None
a => 1
b => 2
c => 3
print(D)
for key in sorted(D):
    print(key, '=>', D[key])
{'a': 1, 'b': 2, 'c': 3}
a => 1
b => 2
c => 3
for c in 'bright':
    print(c.upper())
B
R
I
G
H
T
x = 4
while x>0:
    print('bright!'*x)
    x -= 1
bright!bright!bright!bright!
bright!bright!bright!
bright!bright!
bright!
  • 迭代和优化
squares = [x**2 for x in [1,2,3,4,5]]
print('列表解析: {}'.format(squares))

squares = []
for x in [1,2,3,4,5]:
    squares.append(x**2)
print('一般方法: {}'.format(squares))
列表解析: [1, 4, 9, 16, 25]
一般方法: [1, 4, 9, 16, 25]
  • 丢失键值
print('D: {}'.format(D))

D['e'] = 99 # # Assigning new keys grows dictionaries
print('D: {}'.format(D))

try:
    D['f'] ## Referencing a nonexistent key is an error
except:
    print('没有f这个键')
    print('f' in D)
    if not 'f' in D:
        print('Missing')

value = D.get('x',0) # Index but with a default
print('value 1: {}'.format(value))

value = D['x'] if 'x' in D else 0 # if/else expression form
print('value 2: {}'.format(value))
D: {'a': 1, 'b': 2, 'c': 3}
D: {'a': 1, 'b': 2, 'c': 3, 'e': 99}
没有f这个键
False
Missing
value 1: 0
value 2: 0

元组 = tuples

T = 1,2,3,4
print('Length: {}'.format(len(T)))
print('Concatenation: {}'.format(T+(5,6)))
print('the first element: {}'.format(T[0]))
print('Tuple methods: 4 appears at offset 3: {}'.format(T.index(4)))
print('# 4 appears once: {}'.format(T.count(4)))
T = ('spam', 3.0, [11,22,33])
print('T[1]: {}'.format(T[1]))
print('T[2][1]: {}'.format(T[2][1]))
Length: 4
Concatenation: (1, 2, 3, 4, 5, 6)
the first element: 1
Tuple methods: 4 appears at offset 3: 3
# 4 appears once: 1
T[1]: 3.0
T[2][1]: 22

文件 = file

f = open('data.txt', 'w')# Make a new file in output mode
f.write('Hello\n')# Write strings of bytes to it
f.write('world\n')# Returns number of bytes written in Python 3.0
f.close() # Close to flush output buffers to disk
f = open('data.txt')
text = f.read()
print(text)
print('file content is always a string: {}'.format(text.split()))
Hello
world

file content is always a string: ['Hello', 'world']

集合 = set

X = set('bright')
Y = {'b', 'r','t','a','z'}
X,Y
print('X,Y: {}'.format(X,Y))
print('X&Y: {}'.format(X&Y))
print('X|Y: {}'.format(X|Y))
print('X-Y: {}'.format(X-Y))
print('Set comprehensions in 3.0: {}'.format({x ** 2 for x in [1, 2, 3, 4]}))
X,Y: {'g', 'b', 't', 'h', 'i', 'r'}
X&Y: {'b', 't', 'r'}
X|Y: {'g', 'b', 't', 'h', 'a', 'i', 'z', 'r'}
X-Y: {'g', 'h', 'i'}
Set comprehensions in 3.0: {16, 1, 4, 9}

小数

1/3
0.3333333333333333
2/3 + 1/2
1.1666666666666665
import decimal
d = decimal.Decimal('3.141')
print('d + 1 : {}'.format(d+1))
decimal.getcontext().prec = 2
print('固定精度后的值: {}'.format(decimal.Decimal('1.00')/decimal.Decimal('3.00')))
d + 1 : 4.141
固定精度后的值: 0.33
from fractions import Fraction
f = Fraction(2,3)
print('f+1: {}'.format(f + 1))
f + Fraction(1,2)
f+1: 5/3





Fraction(7, 6)

参考《Learing Python》改编

猜你喜欢

转载自www.cnblogs.com/brightyuxl/p/8974579.html