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》改编

原文地址:https://www.cnblogs.com/brightyuxl/p/8974579.html

时间: 2024-11-26 00:25:34

Python3高级基础(1)的相关文章

Python3 Tkinter基础 Entry state='readonly' 不可写入的输入框,但是可以选中与拷贝

镇场诗: 清心感悟智慧语,不着世间名与利.学水处下纳百川,舍尽贡高我慢意. 学有小成返哺根,愿铸一良心博客.诚心于此写经验,愿见文者得启发.------------------------------------------ code: from tkinter import * root = Tk() content=StringVar() content.set('可以选中') e1=Entry(root, textvariable=content, state='readonly', )

Python3 高级特性

切片 L[0:3]表示,从索引0开始取,直到索引3为止,但不包括索引3.即索引0,1,2,正好是3个元素. 如果第一个索引是0,还可以省略: >>> L =['Michael', 'Sarah', 'Tracy', 'Bob', 'Jack']>>> L[:3] ['Michael', 'Sarah', 'Tracy'] 也可以从索引1开始,取出2个元素出来: >>> L[1:3] ['Sarah', 'Tracy'] 类似的,既然Python支持L[

整理JavaScript高级基础知识

整理JavaScript高级基础知识 因为空余时间很多..所以博客更新频率得相对频繁些.. 原型以及原型链 考察原型以及原型链: var object = {} object.__proto__ === Object.prototype // 为 true var fn = function(){} fn.__proto__ === Function.prototype // 为 true fn.__proto__.__proto__ === Object.prototype // 为 true

[HTTP] 高级基础知识整理

HTTP 高级基础知识 整理 HTTP 高级基础知识,包括 Cookie / Session / localStorage / sessionStorage / Cache-Control / Expires / Etag 等 Cookie cookie :wiki Cookie(复数形态Cookies),又称为"小甜饼".中文名称为"小型文本文件",指某些网站为了辨别用户身份而储存在用户本地终端(Client Side)上的数据(通常经过加密) -wiki coo

python3 day1-python基础

开始python的学习,关于python的介绍及其发展历史这里就不多说了.可以百度一下. 本人也是刚刚开始学习,知识点后续会在补充. 首先我们面临的选择:使用哪个版本开始学习(可以去官网查询,有英文的具体介绍) 一.python2 or python3 2个版本之间的差别有很多,编码.语法.字符串.数据类型.库.类.模块等等.这里理解不深刻先说以下2点. 1.默认编码 python2默认使用的是ascii,所以在读取中文时候会乱码,解决的方法是在文件的开头加上:# -*- coding: UTF

python3.0_day9_scoket基础之篇

一.socket简单介绍 socket通常也称作"套接字",用于描述IP地址和端口,是一个通信链的句柄,应用程序通常通过"套接字"向网络发出请求或者应答网络请求. socket起源于Unix,而Unix/Linux基本哲学之一就是“一切皆文件”,对于文件用[打开][读写][关闭]模式来操作.socket就是该模式的一个实现,socket即是一种特殊的文件,一些socket函数就是对其进行的操作(读/写IO.打开.关闭) 1.socket与file区别: file模块

Python3.6- Python基础介绍

1. 认识Python 1.1. Python发展历史 1.1.1. Python之父--吉多·范罗苏姆 Python的作者,Guido von Rossum(吉多·范罗苏姆),荷兰人.1982年,Guido从阿姆斯特丹大学获得了数学和计算机硕士学位.然而,尽管他算得上是一位数学家,但他更加享受计算机带来的乐趣.用他的话说,尽管拥有数学和计算机双料资质,他总趋向于做计算机相关的工作,并热衷于做任何和编程相关的活儿. 在那个时候,Guido接触并使用过诸如Pascal [?pæsk?l].C.Fo

Python3零基础入门学习视频+源码+课件+习题-小甲鱼

目录 1. 介绍 2. 目录 3. 下载地址 1. 介绍 适用人群 完全零基础入门,不需要任何前置知识. 课程概述 本系列教程面向零基础的同学,是一个深入浅出,通俗易懂的Python3视频教程. 前半部分主要讲解Python3的语法特性,后半部分着重讲解Python3在爬虫.Tkinter.Pygame游戏开发等实例上的应用.整个系列共16个章节,前边13个章节从一个小游戏引入Python,逐步介绍Python的语法以及语言特色.最后3个章节为案例的演示,是前边内容的总结和提高. 其他介绍 2.

[Python3]类基础

概述 Python从设计之初就是面向对象的编程语言,所以在Python中创建一个类和对象是轻而易举的. 本文就Python的面向对象编程进行分享. 几个基本的概念 类(Class)简单理解为具有相同的属性和方法的对象的集合.定义了该集合中每个对象共有的属性和方法,对象是类的实例. 类变量类变量在整个实例化的对象中公用.定义在类中且在函数体外.(少用) 数据成员类变量或实例变量,用于处理类及其实例的数据 方法重写 如果从父类继承的方法满足不了应用,对该方法进行重新实现,这个过程叫override(