Python3高级基础(1)

匿名 (未验证) 提交于 2019-12-02 22:51:30

[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

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')
  • 序列操作
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}
  • 映射操作
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'],        
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!