python学习笔记1

对象类型

对象可认为是需要操作的数据和操作方式;

python程序可分为:模块、语句、表达式和对象。
- 程序由模块构成
- 模块包含语句
- 语句包含表达式
- 表达式建立并处理对象

python特点:不需要部署和管理对象类型,直接使用内置对象。原因为:
- 内置对象程序更容易书写
- 内置对象是可扩展组件
- 内置对象往往比定制化数据结构更有效率
- 内置对象是语言标准的一部分

1234                             # 数字
'asd'                            # 字符串
[1,2,3]                          # 列表
{'a':1, 'b':y}                   # 字典
(1, 'spam', 2)                   # 元组
myfile=open('egg','r')           # 文件
set('abc'),{'a','b','c'}         # 集合

其他类型如:None, bool
编程单元类型:函数、模块、类

列表:提供了其他对象的有序集合
字典:通过键值存储对象

数字

类型:整数、浮点数、复数、固定精度的十进制数、有理分数以及集合

print('整数: %d' % 123)    
print('浮点数: %f' % (10*0.4))
print('集合:%s' % set('abc'))
整数: 123
浮点数: 4.000000
集合:{'b', 'c', 'a'}
运算:加、减、乘、整除、除取整、取余、指数、对数、开方、随机数
import math
import random
​
print('10整除4:%d' % (10//4))
print('10除以4: %f' % (10/4))
print('10除以4取余: %d' % (10%4))
print('10的4次方: %d' % (10**4))
print('以4为底,10的对数: %f' %(math.log(10,4)))
print('10开4次方: %f' %(10**(1/4)))
print('生成一个随机数:%f' % (random.random()))
10整除42
10除以4: 2.500000
10除以4取余: 2
104次方: 100004为底,10的对数: 1.660964
104次方: 1.778279
生成一个随机数:0.368077

字符串

作用:记录文本信息

s = 'spam'
​
print('字符串长度: %d'%len(s))
print('正向索引操作,第一个字符是:%s' % s[1])
print('反向索引操作,第一个字符是:%s' % s[-1])
print('切片操作,第一到三个字符是:%s' % s[:3])

字符串长度: 4
正向索引操作,第一个字符是:p
反向索引操作,第一个字符是:m
切片操作,第一到三个字符是:spa
  • 切片操作始终是从左边界索引到右边界索引减一的位置,且切片和索引均为创建新的字符串
  • 字符串支持加号合并和乘号重复
print('字符串相加:%s'% s+s)
print('字符串重复10次: %s'% (s*10))
print('字符串重复10次: %s'% s*10)
字符串相加:spamspam
字符串重复10次: spamspamspamspamspamspamspamspamspamspam
字符串重复10次: spam字符串重复10次: spam字符串重复10次: spam字符串重复10次: spam字符串重复10次: spam字符串重复10次: spam字符串重复10次: spam字符串重复10次: spam字符串重复10次: spam字符串重复10次: spam
  • 字符串的不可变性(数字、字符串和元组)
  • 寻找和替换(.find, .replace)
  • 取词(.split)
  • 大小写转换(.upper,.lower())
  • 判断是否字母、数字(.isalpha, .isdigit)
  • 移除空格(.rstrip)

/n:newline,window中表示另起一行;
/r:return, 表示回车换行
/t:tab

给字符串中元素直接赋值会发生错误,因字符串为不可变更对象!!!

s[0] = 'fly'
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-7-90bd847ed8c6> in <module>()
----> 1 s[0] = 'fly'

TypeError: 'str' object does not support item assignment
print('%s, eggs, and %s' % ('spam', 'spam!!!'))
'{0}, eggs, and {1}'.format('spam', 'spma!!!')
spam, eggs, and spam!!!
Out[8]:
'spam, eggs, and spma!!!'

寻求帮助

  • 明确数据类型
  • 使用dir函数寻找对应功能
  • 使用help函数了解使用方式
  • 尝试、尝试、再尝试
dir(s)
. . .

help(s.split)
Help on built-in function split:

split(...) method of builtins.str instance
    S.split(sep=None, maxsplit=-1) -> list of strings

    Return a list of the words in S, using sep as the
    delimiter string.  If maxsplit is given, at most maxsplit
    splits are done. If sep is not specified or is None, any
    whitespace string is a separator and empty strings are
    removed from the result.

模式匹配

利用内置re函数和match函数进行文本匹配,用(.*)来寻找对象

import re
​
match1 = re.match('my name is (.*)', 'my name is flying_bird')
match2 = re.match('/(.*)/(.*)/(.*)', '/dl_review/python/lesson6')
match3 = re.match('/(.*)/(.*)/(.*)', '/dl_review/python/lesson6/flying_bird')
print(match1.group(1))
print(match2.groups())
print(match3.groups())
flying_bird
('dl_review', 'python', 'lesson6')
('dl_review/python', 'lesson6', 'flying_bird')

列表List

类型特定操作:append()、extend()、pop()、insert()、remove()和sorted()


L = [1, '123', 1.5]
​
L1 = L.append('3')
print(L1)
print(L.pop(1))
print(L.extend([3, 'stf']))
print(L.insert(2,'sdr'))
print(L.remove(1))
None
123
None
None
None

列表中不允许选择超过边界的元素输出,而在切片操作中是允许的!!!

嵌套

M = [[1, 2, 3],
     [4, 5, 6],
     [7, 8, 9]]
print(M[0][1])
print(M[2])
print(M)
2
[7, 8, 9]
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]

列表解析


print([row[1] for row in M])
print([row[1]+ 1 for row in M])
print([row[1] for row in M if row[1]%2==0])
[2, 5, 8]
[3, 6, 9]
[2, 8]

print([M[i][i] for i in [0, 1, 2]])
print([s * 2 for s in 'spam'])
[1, 5, 9]
['ss', 'pp', 'aa', 'mm']

print([sum(i) for i in M])
print({sum(row) for row in M})
[6, 15, 24]
{24, 6, 15}

字典

字典内部不是序列,而是一种映射操作。
通过键搜索,是python中最快的方法

D={}
​
D['name'] = 'flying_bird'
D['job'] = 'student'
D['age'] = '24'
print(D)
print(D['age'])
{'name': 'flying_bird', 'job': 'student', 'age': '24'}

字典嵌套

当键对应值信息有多种时,会使用到嵌套情况
字典内部可以使用列表、字典或者其他类型,灵活的使用嵌套可大大提高数据的可用性

D['name'] = {'first_name': 'shi', 'last_name': 'tengfei'}
print(D)
{'name': {'first_name': 'shi', 'last_name': 'tengfei'}, 'job': 'student', 'age': '24'}

字典内部存储键的顺序是无序的,因此输入和输出的排序可能不一样。
当要将键值排序是,一般用keys()来获取键,利用sorted()来排列,利用for循环来遍历输出

N = {'a': 'apple', 'c':'car', 'b':'banana'}
​
print(N)
​
print(list(N.keys()))
​
print(sorted(list(N.keys())))
print()
#for key in sorted(N):
#    print(key, '=>', N(key))
{'a': 'apple', 'c': 'car', 'b': 'banana'}
['a', 'c', 'b']
['a', 'b', 'c']

x = 5
while x>0:
    print('flying_bird  '*x)
    x -= 1
flying_bird  flying_bird  flying_bird  flying_bird  flying_bird  
flying_bird  flying_bird  flying_bird  flying_bird  
flying_bird  flying_bird  flying_bird  
flying_bird  flying_bird  
flying_bird  
  • 列表解析和相关函数编程工具如map何fliter,通常运行比for循环快(两倍左右)
  • 从下面两段程序可以看出,for循环处理1000000个数字和列表解析速度相当且在python3.6版本中,用列表解析更快一些!
import numpy as np
​
a = np.random.random(1000000)
​
def function1(a):
    b = []
    for i in a:
        b.append(i * 10)
​
%time c = [i*10 for i in a]
Wall time: 291 ms
In [93]:

%time function1(a)
Wall time: 381 ms

利用get方法来获取字典中键:dict.get(key, 否则输出后者)

N.get('d', 0)
0

元组(Tuple)

专用方法:index(返回索引值);count(返回出现次数)
特点:创建后不可改变,也支持索引和切片操作。

P = (1, 2, '123', 'ste', 1.23)
​
print(P[1:3])
print(len(P))
print(P + (1, 2.4))
print(P.index(1))
print(P.count(1.23))
(2, '123')
5
(1, 2, '123', 'ste', 1.23, 1, 2.4)
0
1

使用元组原因:在不需要随意改变数据内容时使用

文件(file)

  • 一般是调用内置函数open来存取文件,声明模式如’r’,’w’等
  • read()读取整个原始文本;readline()读取文本第一行;readlines()读取文本每一行;
  • split()默认取单个词汇,可选择空格、回车换行等分词。
filename = 'lenses.txt'
file = open(filename, 'r')
text = file.read().split(' ')
text
Out[123]:
['young\tmyope\tno\treduced\tno',
 'lenses\nyoung\tmyope\tno\tnormal\tsoft\nyoung\tmyope\tyes\treduced\tno',
 'lenses\nyoung\tmyope\tyes\tnormal\thard\nyoung\thyper\tno\treduced\tno',
 'lenses\nyoung\thyper\tno\tnormal\tsoft\nyoung\thyper\tyes\treduced\tno',
 'lenses\nyoung\thyper\tyes\tnormal\thard\npre\tmyope\tno\treduced\tno',
 'lenses\npre\tmyope\tno\tnormal\tsoft\npre\tmyope\tyes\treduced\tno',
 'lenses\npre\tmyope\tyes\tnormal\thard\npre\thyper\tno\treduced\tno',
 'lenses\npre\thyper\tno\tnormal\tsoft\npre\thyper\tyes\treduced\tno',
 'lenses\npre\thyper\tyes\tnormal\tno',
 'lenses\npresbyopic\tmyope\tno\treduced\tno',
 'lenses\npresbyopic\tmyope\tno\tnormal\tno',
 'lenses\npresbyopic\tmyope\tyes\treduced\tno',
 'lenses\npresbyopic\tmyope\tyes\tnormal\thard\npresbyopic\thyper\tno\treduced\tno',
 'lenses\npresbyopic\thyper\tno\tnormal\tsoft\npresbyopic\thyper\tyes\treduced\tno',
 'lenses\npresbyopic\thyper\tyes\tnormal\tno',
 'lenses\n']

dir(file)
. . .

help(file.read)
Help on built-in function read:

read(size=-1, /) method of _io.TextIOWrapper instance
    Read at most n characters from stream.

    Read from underlying buffer until we have n characters or we hit EOF.
    If n is negative or omitted, read until EOF.

课后练习

  • 1.列举python核心数据类型名称?
    数值、列表、元组、字典、字符串

  • 2.为何成为核心类型?
    因为它们是语言的一部分,且总是有效

  • 3.不可变性代表什么?哪三种是不可变得?
    建立之后不可改变,有元组、字符串和数字。虽然不可改变,但可以新建。

  • 4.序列是什么意思?哪三种是属于这个分类?
    序列意味着对对象位置进行排序的集合。字符串、列表和元组是python中所有序列。

  • 5.映射是什么意思?哪种是这个类型?
    映射表示从一个键与值的对应关系,字典属于这个类型,字典中键没有顺序排列,可选取sorted进行排序。

  • 6.多态是什么意思?为什么要关心多态?
    操作符的作用取决于被操作对象,是python的关键思想之一,让代码自动适用于多种类型

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值