一 数值
int(整型)
long(长整型[也可以代表八进制和十六进制])
float(浮点型)
complex(复数)
需要注意的是:在Python2以后的版本中,没有长整型,被int替代。
Python2中:
>>> l=12345666666666666666666666666698
>>> type(l)
<type 'long'>
Python3中:
>>> l=12366666666666666666896666666668
>>> type(l)
<class 'int'>
另外:还有特殊的布尔类型(只有True和False两种)
注意:Python中数据类型也可进行转换
二 字符串
字符串属于序列,序列支持的操作(特性)如下:
1)索引
2)切片
3)成员操作符
4)重复
5)拼接
6)计算长度
python的字串列表有2种取值顺序:
从左到右索引默认0开始的,最大范围是字符串长度少1
从右到左索引默认-1开始的,最大范围是字符串开头
如下示例:
| a | b | c | d | e | f |
| 0 | 1 | 2 | 3 | 4 | 5 |
| -6| -5| -4|-3| -2| -1|
索引:
>>> s='hello world'
>>> s[0]
'h'
>>> s[4]
'o'
>>> s[-6]
' '
>>> s[-4]
'o'
>>>
切片:
s[start:end:step] 从start开始到end-1结束, 步长为step;
s[start:end] 获取的子字符串包含start字符,但不包含end的字符
如果start省略, 则从头开始切片,不包含end字符
如果end省略, 一直切片到字符串最后
>>> s='learn python'
>>> s[2:]
'arn python'
>>> s[:-3]
'learn pyt'
>>> s[4:7]
'n p'
>>> s[3:8:2]
'r y'
>>> s[::-1] #反转
'nohtyp nrael'
>>> s[:] #拷贝
'learn python'
成员操作符:
>>> s = "hello"
>>> 'h' in s
True
>>> 'hel' in s
True
>>> 'oo' in s
False
>>> 'h' not in s
False
>>> 'oo' not in s
True
重复:
>>> s='learn python'
>>> s*2
'learn pythonlearn python'
>>> s*3
'learn pythonlearn pythonlearn python'
>>>
拼接:
>>> a = "hello"
>>> b = "python"
>>> print("%s %s" %(a, b))
hello python
>>> a + b
'hellopython'
>>> a + " " +b
'hello python'
计算长度:
>>> s='hello world'
>>> len(s)
11
字符串常用方法
Ps:字符串方法有很多,但是在这里我只列举常用的,了解更多的话用dir()
str.capitalize()
将字符串首字母大写
str.center(width[,fillchar])
返回一个长为width的新字符串,其他部分用fillchar指定的符号填充,未指定时通过空格填充
>>> s='hello world'
>>> s.center(40,'*')
'**************hello world***************'
str.count(sub[, start[, end]])
返回sub在str中出现的次数,如果start与end指定,返回指定范围内的sub出现次数。
>>> s='like python,learn python'
>>> s.count('h')
2
>>> s.count('h',5)
2
>>> s.count('h',8,18)
1
str.endswith(suffix[, start[, end]])
判断字符串是否以suffix结束,如果start和end指定,则返回str中指定范围内str子串是否以suffix结尾,如果是,返回True;否则返False
str.startswith(prefix[, start[, end]])
同上边的endswith
str.find(sub[,start[,end]])
判断sub是否在str中,存在返回索引值,不存在返回-1.
str.index(sub[,start[,end]])
与find方法函数功能相同,如果sub不存在时抛出ValueError异常;
>>> s='helloood'
>>> s.find('e')
1
>>> s.find('o') #第一次查找的时候会从左到右找出第一个
4
>>> s.rfind('o') #第二次查找
6
>>> s.find('x')
-1
>>> s.index('h')
0
>>> s.index('x')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: substring not found
str.join(seq)
以str作为分隔符,将序列seq中的所有元素合并为一个新的字符串。
str.split([sep)
以sep字符串作为分割符对str进行切割,默认为空格
str.replace(old,new[,count])
将str中的old字符串替换为new字符串,并将替换后的新字符串返回,如果count指定,则只替换前count个字符串
>>> ip = ['172', '25', '254', '19']
>>> "".join(ip)
'1722525419'
>>> "*".join(ip)
'172*25*254*19'
>>> ip1 = "1172.25.254.19"
>>> ip1.split('.')
['1172', '25', '254', '19']
>>> date = "2018-2-30"
>>> date.split("-")
['2018', '2', '30']
>>> date.replace('-', '/')
'2018/2/30'
str.strip([chars])
返回一字符串,将str中首尾包含指定的chars字符删除的字符串,未指定时,删除首尾的空格。空格为广义的空格, 包括: \n, \t, \r
>>> s = " hello "
>>> s.strip()
'hello'
>>> s.lstrip() #去掉左边的空格
'hello '
>>> s.rstrip() #去掉右边的空格
' hello'
>>> s.strip('he')
'llo'
>>> s.lstrip('he')
'llo'
str.isalnum()
判断是否都是字母或数字
str.isalpha()
判断是否都是字母
str.isdigit()
判断是否都是数字
str.islower()
判断是否都是小写
str.isspace()
判断是否都是英文空格
str.istitle()
判断是不是都是标题(有大小写)
str.isupper()
判断是不是都为大写字母
三 列表
- 列表用 [ ] 标识
- 定义一个空列表 :list = [ ]
定义一个包含元素的列表,元素可以是任意类型,包括数值类型,列表,字符串等.并且列表里面也是可以嵌套列表的
>>> l=['hello',True,88,98.78,4j+8,(10,'male')]
>>> type(l)
<class 'list'>
>>> ll=[9,'world',8.9,[1,2.3,'nihao']]
>>> type(ll)
<class 'list'>
注:列表同样支持索引,切片,成员操作符,重复,拼接,计算长度
列表常用方法
- 列表的添加
列表可通过append方法添加元素
列表可通过方法extend添加元素
在指定位置添加元素使用inert方法
>>> li=[12,23,34,45]
>>> li.append(56) #追加一个值到列表末尾
>>>
>>> li
[12, 23, 34, 45, 56]
>>> li.extend([78,89,90]) #追加多个值到列表末尾
>>> li
[12, 23, 34, 45, 56, 78, 89, 90]
>>> li.insert(2,90) #将对象插入到列表指定位置
>>> li
[12, 23, 90, 34, 45, 56, 78, 89, 90]
- 列表的修改
通过索引值修改列表的元素:直接重新赋值
>>> li1=['lijia',20,'female']
>>> li1[0]='sunyue'
>>> li1
['sunyue', 20, 'female']
- 列表的查看
查看某个列表元素的索引值用index方法;
查看某个列表元素出现的次数用count方法;
排序查看用sort方法,按照Ascill进行排序 - 列表的删除
list.remove(list[ ])
del(list[ ])
list.clear()
>>> li=['fentiao',5,'male',True]
>>> li.remove('male') #直接删除指定元素
>>> li
['fentiao', 5, True]
>>> li.remove(li[2]) #通过索引删除指定元素
>>> li
['fentiao', 5]
>>> del(li[1]) #通过索引删除指定元素
>>> li
['fentiao']
>>> del(li) #删除列表
>>> li
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'li' is not defined
>>> li.clear() #清空列表内容
>>> li
[ ]
- 列表的复制,反转
copy,reverse
四 元组
- 元组用"( )"标识。内部元素用逗号隔开。
- 定义空元组
tuple = () - 定义单个值的元组
tuple = (fentiao,) - 一般的元组
tuple = (fentiao, 8, male)
元组: 不可变数据类型,没有增删改查;可以存储任意数据类型;
>>> t=(2,True,'hello',4.6,(3,4,5),[2,'s',6])
>>> type(t)
<class 'tuple'>
注:元组可执行的操作支持索引,切片,成员操作符,重复,拼接,计算长度
!!!如果元组里面包含可变数据类型, 可以间接修改元组内容;
>>> t[5].append('hi')
>>> t
(2, True, 'hello', 4.6, (3, 4, 5), [2, 's', 6, 'hi'])
元组常见方法
- 元组的赋值: 有多少个元素, 就用多少个变量接收
>>> t = ('westos', 10, 100)
>>> name, age,score = t
>>> print(name, age, score)
westos 10 100
- 返回value在元组中出现的次数
t.count(value) - 返回value在元组中的索引值
t.index(value) - 删除元组
del(tuple)
五 字典
- 字典用"{ }"标识。
- 字典由索引(key)和它对应的值value组成。字典是无序的对象集合
- 字典对象是可变的,但key必须用不可变对象,value值可以是任意数据类型:(int, float,long, complex, list, tuple,set, dict)
- 定义空字典:
s={ },
s=dict( ) - 赋值: d = {‘key’:‘value’, ‘key1’:‘value1’}
- 根据已有数据类型创建字典
>>> d=dict(a=1,b=2)
>>> d
{'a': 1, 'b': 2}
>>> type(d)
<class 'dict'>
>>> users=['user1','user2']
>>> passwds=['123','456']
>>> print(list(zip(users,passwds)))
[('user1', '123'), ('user2', '456')]
>>> print(dict(zip(users,passwds)))
{'user1': '123', 'user2': '456'}
注:字典支持成员操作符
>>> d=dict(a=1,b=2)
>>> print('a' in d) #通过key值访问
True
>>> print(1 in d)
False
字典值的访问
- 通过key值来访问,key值不存在会报错
>>> d={'name':'lijia','age':20,'gender':'female'}
>>> d['age']
20
- 循环遍历访问
>>> for i in d:
... print(i)
...
name
age
gender
- 枚举
>>> for i,v in enumerate(d):
... print(i,'--->',v)
...
0 ---> name
1 ---> age
2 ---> gender
字典的方法
字典的添加
>>> d={'name':'lijia','age':20,'gender':'female'}
>>> d['score']=90 #添加key-value
>>> d
{'name': 'lijia', 'age': 20, 'gender': 'female', 'score': 90}
>>> d['gender']='male' #如果key存在,则是替换value值
>>> d
{'name': 'lijia', 'age': 20, 'gender': 'male', 'score': 90}
update
- 如果key值已经存在, 更新value值;
- 如果key值不存在, 添加key-value值;
>>> d.update({'name':'westos','height':1.6})
>>> d
{'name': 'westos', 'age': 20, 'gender': 'male', 'score': 90, 'height': 1.6}
setdefault
- 如果key值已经存在, 不做修改;
- 如果key值不存在, 添加key-value值;默认情况下value值为None,如果需要指定值,传值即可。
>>> d.setdefault('age',19)
20
>>> d.setdefault('weight')
>>> d
{'name': 'westos', 'age': 20, 'gender': 'male', 'score': 90, 'height': 1.6, 'weight': None}
字典的删除
pop
- 根据key值删除指定元素,并弹出value值
>>> d.pop('height')
1.6
>>> d
{'name': 'westos', 'age': 20, 'gender': 'male', 'score': 90, 'weight': None}
popitem
- 随机删除字典中的元素
>>> d.popitem()
('weight', None)
>>> d
{'name': 'westos', 'age': 20, 'gender': 'male', 'score': 90}
clear
- 删除字典中所有元素
>>> d.clear()
>>> d
{}
del
- 删除字典本身或者删除指定的key
>>> d=dict(a=1,b=2,c=3)
>>> del d['b']
>>> d
{'a': 1, 'c': 3}
>>> del d
>>> d
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'd' is not defined
字典的修改和查看
dic.get()
- 如果key存在于字典中,则返回value值
>>> d={'name':'westos','age':19,'gender':'male'}
>>> d.get('name')
'westos'
dic.keys()
- 返回字典的所有key值
>>> d.keys()
dict_keys(['name', 'age', 'gender'])
dic.values()
- 查看字典里面所有的value值
>>> d.values()
dict_values(['westos', 19, 'male'])
dic.items()
- 查看字典里面所有的key-value值
>>> d.items()
dict_items([('name', 'westos'), ('age', 19), ('gender', 'male')])
- 查看指定key对应的value值, 注意: key不存在, 就会报错
>>> d['age']
19
>>> d['height']
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'height'
- 遍历(直接和间接)
>>> for k,v in d.items():
... print(k,'--->',v)
...
name ---> westos
age ---> 19
gender ---> male
>>> for k in d:
... print(k,'--->',d[k])
...
name ---> westos
age ---> 19
gender ---> male
六 集合
- 定义空集合
s=set( ) 或者 s=set([ ])
s={ }默认的是字典
>>> s={}
>>> print(s,type(s))
{} <class 'dict'>
- 定义集合
>>> s1={1,2,3,'hello'}
>>> print(s1,type(s1))
{1, 2, 3, 'hello'} <class 'set'>
>>> s2={1,2,3,'hello',(1,2,3)}
>>> print(s2,type(s2))
{1, 2, 3, 'hello', (1, 2, 3)} <class 'set'>
>>> s3={1,2,3,'hello',(1,2,3),[1,2,3]}
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'
- 集合里面的元素不可重复,可作如下应用:
- 列表去重
-关系测试:如交集、差集、并集的关系测试
注:集合的特性支持成员操作符,也可计算长度
- 集合中的for循环
>>> s={1,2,3,'hello'}
>>> for i in s:
... print(i,end='--')
...
1--2--3--hello-->>>
- for + index
>>> for k,v in enumerate(s):
... print(k,'--->',v)
...
0 ---> 1
1 ---> 2
2 ---> 3
3 ---> hello
集合的方法
- 集合是可变, 无序数据类型,添加的顺序,和在集合中存储的顺序不同;
- 添加
set.add()
>>> s={5,6,3,4,3,2}
>>> s.add(7)
>>> print(s)
{2, 3, 4, 5, 6, 7}
set.update()
>>> s.update({7,8,9})
>>> print(s)
{2, 3, 4, 5, 6, 7, 8, 9}
- 删除
set.remove()
>>> s.remove(5) #删除指定元素
>>> print(s)
{2, 3, 4, 6, 7, 8, 9}
set.pop()
>>> s.pop() #随机删除元素,并返回删除的元素
2
>>> print(s)
{3, 4, 6, 7, 8, 9}
set.clear()
>>> s.clear() #清空集合所有元素
>>> print(s)
set()
s.copy()
- 集合的浅拷贝
- 关系:并集, 交集, 差集,对等差分: 并集-交集
并集:
>>> s1={1,2,3,4}
>>> s2={3,4,5,6}
>>> print('并集:',s1.union(s2)) #或者 (s1 | s2)
并集: {1, 2, 3, 4, 5, 6}
交集:
>>> print('交集:',s1.intersection(s2)) #或者 (s1 & s2)
交集: {3, 4}
差集:
>>> print('差集:',s1.difference(s2)) #或者(s1-s2)
差集: {1, 2}
>>> print('差集:',s2.difference(s1)) #或者(s2-s1)
差集: {5, 6}
对等差分:并集-交集
>>> print('对等差分:',s1.symmetric_difference((s2))) #或者(s1^s2)
对等差分: {1, 2, 5, 6}
子集,父集,交集判断
>>> s={1,2}
>>> s1={1,2,3}
>>> print(s.issubset(s1))
True
>>> print(s.issuperset(s1))
False
>>> print(s.isdisjoint(s1))
False
拓展:
深拷贝与浅拷贝
-
直接赋值(li1 = li): 只传递对象的引用, li1指向对象li的内存地址空间,因此, 原有列表li改变, 被赋值的li1也会做相应的改变.
-
浅拷贝(三种实现方式 eg: li2=li.copy()):li和li2的内存地址不同,但是子对象的内存地址相同, 因此,原始数据改变 ,子对象也改变.
-
深拷贝(import copy, eg: li3=copy.deepcopy(li)), li和li3的内存地址不同,包含子对象的拷贝, 所以原始对象改变并不会造成深拷贝里面任何子项的改变.
当深拷贝和浅拷贝, 针对的对象全部是不可变数据类型时, 两者效果相同; -
浅拷贝的实现:
li.copy()
li[:]
copy.copy(li) -
实现深拷贝:
copy.deepcopy(li)
>>> li=[1,2,3]
>>> li1=li
>>> li
[1, 2, 3]
>>> li1
[1, 2, 3]
>>> id(li)
139907445186504
>>> id(li1)
139907445186504
>>> li2=li[:]
>>> li.append(4)
>>> li
[1, 2, 3, 4]
>>> li2
[1, 2, 3]
>>> id(li)
139907445186504
>>> id(li2)
139907445185672
>>> li3=li.copy()
>>> li.append(5)
>>> li
[1, 2, 3, 4, 5]
>>> li3
[1, 2, 3, 4]
>>> id(li)
139907445186504
>>> id(li3)
139907445183304
>>> import copy
>>> li4=copy.copy(li)
>>> li.append(9)
>>> li
[1, 2, 3, 4, 5, 9]
>>> li4
[1, 2, 3, 4, 5]
>>> id(li)
139907445186504
>>> id(li4)
139907324685192
>>> li5=copy.deepcopy(li)
>>> li.append(8)
>>> li
[1, 2, 3, 4, 5, 9, 8]
>>> li5
[1, 2, 3, 4, 5, 9]
>>> id(li)
139907445186504
>>> id(li5)
139907324685256
is 和 ==的区别
变量:
id: 在内存中存储的位置;
value: ==
type:变量的数据类型;
==: 判断value, type
is: 三个都判断
a is b ---> True, a==b一定相等, 返回True;
a==b ----> True, a is b 不一定;