Python语言的特殊之处
本人是在有其他语言的基础之上,开始学习Python,因此本文的介绍之包含Python语言的特殊语法和原理。
1 变量
-
类型:Python变量的声明不需要类型,它的真实类型取决于关联的对象。
获取一个变量的类型用函数 type(name)
-
获取变量指向的内存地址 id(name)
-
==与is:==比较值是否相同,is比较的是地址是否相同
注意:int类型的【-5,256】已被Python缓存
4.获取某个字面量值的引用次数
import sys
sys.getrefcount(20)
2 Python的核心数据类型
2.1 数字
(1)int
无限精度,仅受限于计算机内存和配置
(2)float---注意float类型的精度问题
>>> f = 1.1111111
>>> 'f={0:.2f}'.format(f) #格式化
'f=1.11'
>>>'f={0:.2e}'.format(f) #科学计数法
'f=1.11e+00'
>>> 10 / 4
2.5
>>> 10 // 4
2
>>> 10 // 4.0
2.0
>>> math.floor(3.9) #向左取整
3
>>> math.floor(-3.4)
-4
>>> math.trunc(3.9) #向0取整
3
>>> math.trunc(-3.4)
-3
>>> round(3.9) #四舍五入
4
>>> round(-3.4)
-3
>>> 0o7 #八进制
7
>>> 0xa #十六进制
10
>>> on10 #二进制
10
>>> oct(64)
'0o100'
>>> hex(64)
'0x40'
>>> bin(64)
'0b1000000'+
(3)Decimal
>>> import decimal
>>> decimal.Decimal('3.14')
Decimal('3.14')
>>> decimal.Decimal('1.1')+decimal.Decimal('2.2')
Decimal('3.3')
(4)Fraction
(5)boolean(本质上是int1/0)
True or False,
>>> type(True)
<class 'bool'>
>>> isinstance(True,int)
True
>>> True == 1
True
>>> False == 0
True
2.2 字符串str
字符串可用单引号和双引号,也可通过下标获取具体某个字符,name[0]
获取字符串长度:len(name)
字符串拼接与字符串
>>> name = 'Tom'
>>> name[0]
'T'
>>> name + 'jerry'
'Tomjerry'
>>> name * 3
'TomTomTom'
>>> path='C:\abc'
>>> path
'C:\abc'
>>> path=r'c:abc' #忽略转义
>>> path
'c:\abc'
>>> print('-' * 20)
--------------------
#字符串的索引操作
>>> s = '1234567879'
>>>
>>> s[0:4] #获取索引从0-4,不包括4的所有字符
'1234'
>>> s[-1] #获取字符串的最后一个字符
'9'
>>> s[:] #从头到尾获取字符
'1234567879'
>>> s[::2] #从头到尾每隔一个获取一个字符
'13577'
>>>
>>> s[::-1] #反转字符串
'9787654321'
>>> s[::-2] #反转后每隔一个获取一个字符
'98642'
>>> ord('c') #获取字符串的ACSII
99
>>> chr(99) #获取ASCII代表的字符
'c'
#格式化字符串
>>> a = 1
>>> b = 2
>>> a,b = b,a
>>> a
2
>>> b
1
>>> '{0} => {1}'.format(a,b)
'2 => 1'
>>> '{} => {}'.format(a,b)
'2 => 1'
>>> '{name} => {age}'.format(name='Tom',age=20)
'Tom => 20'
2.3 列表list
-
任意对象的有序集合
-
通过索引下标访问元素
-
可变长度
-
属于可变序列
#list与str
>>> s = '0123456789'
>>> l = list(s)
>>> l
['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
>>> l[-1] = '10'
>>> l
['0', '1', '2', '3', '4', '5', '6', '7', '8', '10']
>>> s = ''.join(l)
>>> s
'01234567810'
>>> s = '|'.join(l)
>>> s
'0|1|2|3|4|5|6|7|8|10'
#判断list是够包含某个字符串
>>> '1' in l
True
>>> [1,2,3]+[4,5,6]
[1, 2, 3, 4, 5, 6]
>>> l = [1,2,3,4]
>>> res = []
>>> for c in l:
... res.append(c ** 2)
...
>>> res
[1, 4, 9, 16]
>>> l1 = [i ** 2 for i in l]
>>> l1
[1, 4, 9, 16]
>>> [c*2 for c in 'XYZ']
['XX', 'YY', 'ZZ']
>>> l = [1,2,3]
>>> l[1:2] = [4,5]
>>> l
[1, 4, 5, 3]
>>> ['abc','xyz']*3
['abc', 'xyz', 'abc', 'xyz', 'abc', 'xyz']
>>> l = [1,2,3,4]
>>> l.append(5)
>>> l
[1, 2, 3, 4, 5]
>>> l.extend([9,8,5])
>>> l
[1, 2, 3, 4, 5, 9, 8, 5]
>>> l.sort()
>>> l
[1, 2, 3, 4, 5, 5, 8, 9]
>>> l.reverse()
>>> l
[9, 8, 5, 5, 4, 3, 2, 1]
>>> l.pop()
1
>>> l
[9, 8, 5, 5, 4, 3, 2]
>>> del(l[0]) #这时一个全局函数
>>> l
[8, 5, 5, 4, 3, 2]
>>> l.index(5)
1
>>> l.count(5)
2
#list是引用类型
>>> l1 = [1,2,3,4]
>>> l2 = l1
>>> l1[0] = 8
>>> l1
[8, 2, 3, 4]
>>> l2
[8, 2, 3, 4]
>>> l1 = [1,2,3,4]
>>> l2 = l1[:]
>>> l1[0] = 8
>>> l1
[8, 2, 3, 4]
>>> l2
[1, 2, 3, 4]
>>> l1 = [1,2,3,4]
>>> l2 = l1.copy()
>>> l1[0] = 8
>>> l1
[8, 2, 3, 4]
>>> l2
[1, 2, 3, 4]
2.4 字典表dict
>>> d = {'ISBN':'sldkfjs','Title':'Python','Price':120.00}
>>> d
{'ISBN': 'sldkfjs', 'Title': 'Python', 'Price': 120.0}
>>> d['Title']
'Python'
>>> d['Author'] = 'gdy'
>>> d
{'ISBN': 'sldkfjs', 'Title': 'Python', 'Price': 120.0, 'Author': 'gdy'}
>>> d.get('price',0.0)
0.0
>>> emp = dict(name='Mike',age=20,job='dev')
>>> emp
{'name': 'Mike', 'age': 20, 'job': 'dev'}
>>> len(emp)
3
>>> dep = {'department':'技术部'}
>>> emp.update(dep)
>>> emp
{'name': 'Mike', 'age': 20, 'job': 'dev', 'department': '技术部'}
>>> emp.pop('age')
20
>>> emp
{'name': 'Mike', 'job': 'dev', 'department': '技术部'}
>>>
type(emp.keys())
<class 'dict_keys'>
>>> emp.values()
dict_values(['Mike', 'dev', '技术部'])
>>> type(emp.values())
<class 'dict_values'>
>>> type(emp.items())
<class 'dict_items'>
>>> emp.items()
dict_items([('name', 'Mike'), ('job', 'dev'), ('department', '技术部')])
>>> for k,v in emp.items():print('{}->{}'.format(k,v))
name->Mike
job->dev
department->技术部
>>> ks = list(emp.keys())
>>> ks
['name', 'job', 'department']
2.5 元组tuple
-
-
通过下标访问
-
属于不可变类型
-
长度固定,任意类型,任意嵌套
>>> 1,2
(1, 2)
>>> (1,2)
(1, 2)
>>> x = 1,
>>> x
(1,)
>>> x = (1,)
>>> x
(1,)
>>> len(x)
1
>>> x,y = 5,10
>>> x,y = y,x
>>> x
10
>>> y
5
>>> res = []
>>> t = (1,2,3,4)
>>> for x in t : res.append(x ** 2)
>>> res
[1, 4, 9, 16]
>>> res = [x ** 2 for x in t]
>>> res
[1, 4, 9, 16]
>>> t.index(2)
1
>>> t.count(2)
1
>>> from collections import namedtuple
>>> Employee = namedtuple('Employee',['name','age','salary'])
>>> jerry = Employee(name='jerry',age=20,salary=200.0)
>>> jerry.name
'jerry'
>>> jerry.age
20
>>> tom = Employee('aaa',20,1122.0)
2.7 文件file
mode:
-
r 读
-
w 写
-
a 追加
-
b 二进制
- + (读写)
f = open('hello.txt','w')
f.write('hello ')
f.write('中国 ',encoding='utf8')
f.close()
f = open('hello.txt','r')
f.read() #全部读取
f.readline() #获取一行
f.readlines() #获取所有行
f = open('data.bin','rb') #读取二进制文件
序列化:
import pickle
d = {'a':1,'b':2}
f = open('data.pkl','wb')
pickle.dump(d,f)
f.close()
f = open('data.pkl','rb')
data = pickle.load(f)
data.get('a')
#自动释放f,不需要显示调用f.close()
with open('a.txt','r') as f
for line in f.readlines():
print(line)
2.8 集合Set
2.9 空None