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

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

  1. Python3高级基础(2)

    1 Python3模拟数据结构 1.1 栈 栈是计算机中经典的数据结构,简单的说,栈就是限制在一端进行插入删除操作的线性表.栈有两种最重要的操作,即pop(从栈顶弹出一个元素)和push(将一个元素进 ...

  2. Python3高级核心技术97讲

    可以毫不夸张的说:这门课程是初中级Python开发人员向高级进阶的必学课程 许多Pythoner喜欢追求新的框架,但却不重视Python本身基础知识的学习, 他们不知道的是,语言本身的进阶优先于框架, ...

  3. 微信小程序高级基础

    微信小程序高级基础 微信小程序的注册和服务器配置: 小程序是什么呢?小程序是一种不需要下载安装就可以使用的应用,它实现了应用"触手可及"的梦想,用户扫一扫或者搜一下就可以打开应用, ...

  4. python3高级编程

    1. SMTP发送邮件 internet相关协议: http:网页访问相关,httplib,urllib,xmlrpclib ftp:文件传输相关, ftplib, urllib nntp:新闻和帖子 ...

  5. Java 高级基础——反射

    Java 高级基础--反射 反射的意义:Java 强类型语言,但是我们在运行时有了解.修改信息的需求,包括类信息.成员信息以及数组信息. 基本类型与引用类型 基本类型,(固定的 8 种) 整数:byt ...

  6. python_way ,day1 编译安装python3、基础及流程控制

    本节内容: 1,Python介绍发展史 2,安装 3,Hello World 4,程序 5,变量,字符编码 6,用户输入 7,模块初识 一.python介绍 python的创始人为吉多·范罗苏姆(Gu ...

  7. python3.0_day9_scoket基础之篇

    一.socket简单介绍 socket通常也称作"套接字",用于描述IP地址和端口,是一个通信链的句柄,应用程序通常通过"套接字"向网络发出请求或者应答网络请求 ...

  8. python3【基础】-赋值与深浅拷贝

    一.Python的变量及其存储 在高级语言中,变量是对内存及其地址的抽象.对于python而言,python的一切变量都是对象,变量的存储,采用了引用语义的方式,存储的只是一个变量的值所在的内存地址, ...

  9. Python全栈工程师(Python3 所有基础内容 0-0)

    ParisGabriel              每天坚持手写  一天一篇  决定坚持几年 为了梦想为了信仰    开局一张图     Python一个月的基础语法 基本就到这咯    接下来是数据 ...

随机推荐

  1. python日志和异常

    “日志”转载:http://www.cnblogs.com/dkblog/archive/2011/08/26/2155018.html "异常"转载:http://www.cnb ...

  2. C语言函数调用栈(三)

    6 调用栈实例分析 本节通过代码实例分析函数调用过程中栈帧的布局.形成和消亡. 6.1 栈帧的布局 示例代码如下: //StackReg.c #include <stdio.h> //获取 ...

  3. KVM -> 虚拟机在线热添加技术_04

    热添加技术 1.KVM在线热添加硬盘

  4. 使用NGINX+Openresty和unixhot_waf开源防火墙实现WAF功能

    使用NGINX+Openresty实现WAF功能 一.了解WAF1.1 什么是WAF Web应用防护系统(也称:网站应用级入侵防御系统 .英文:Web Application Firewall,简称: ...

  5. Webpack devServer中的 proxy 实现跨域

    Webpack dev server使用http-proxy解决跨域问题 文档资料 webpack关于webpack-dev-server开启proxy的官方介绍Vue-cli proxyTable ...

  6. 搭建ssh框架项目(三)

    一.创建业务层 (1)创建业务层接口IElecTextService.java package com.cppdy.ssh.service; import com.cppdy.ssh.domain.E ...

  7. sql基础笔记备忘

    MySQL中定义数据字段的类型对你数据库的优化是非常重要的. MySQL支持多种类型,大致可以分为三类:数值.日期/时间和字符串(字符)类型. 数值类型:tinyint smallint medium ...

  8. js有关事件驱动

    事件驱动               /*                 什么是事件?                 1.事件发生了                 2.我要对这个事件做对应的处理 ...

  9. 集合Arraylist的方法的使用和打印

    package chapter090; import java.util.ArrayList;import java.util.List; public class TestList01 { publ ...

  10. 异构平台同步(mysql-->oracle)

    https://www.cnblogs.com/andy6/p/6159060.html