1 2 3

Python3数据类型

最近在学习Python,记录一下学习笔记
 

Python3 一般常用数据类型实例:

int 

 1 """
 2 int内部功能
 3 """
 4 
 5 #返回该数字占用的最少位
 6 num = 888
 7 result = num.bit_length()
 8 print(result)
 9 
10 #返回该复数的共轭复数
11 num = 888
12 result = num.conjugate()
13 print(result)
14 
15 #返回绝对值
16 num = -888
17 result = num.__abs__()
18 print(result)
19 
20 #相加
21 num = 10
22 result = num.__add__(10)
23 print(result)
24 
25 #相除,得到商和余数,返回的是一个元组类型
26 num = 10
27 result = num.__divmod__(3)
28 print(result)
29 
30 #相除,得到商,返回整数
31 num = 10
32 result = num.__floordiv__(3)
33 print(result)
34 
35 #转换为浮点类型
36 num = 10
37 result = num.__float__()
38 print(result)
39 
40 #格式化
41 result = '{0} is {1}'.format("eric","sb")
42 print(result)
43 
44 #返回当前数字的十六进制值
45 result = hex(10)
46 print(result)
47 
48 #转换为整数
49 num = 10.9
50 result = num.__int__()
51 print(result)
52 
53 按位求反
54 #num = 10
55 result = num.__invert__()
56 print(result)
57 
58 #
59 num = 10
60 result = num.__or__(10)
61 print(result)
62 
63 #幂次方
64 num = 10
65 result = num.__pow__(2)
66 print(result)
67 
68 #转换成解析器可阅读的格式
69 num = 10
70 result = num.__repr__()
71 print(result)
72 
73 #转换成人可阅读的格式
74 num = 10
75 result = num.__str__()
76 print(result)
View Code

 

str

"""
字符串内部功能
"""

#字符串居中,两边空出20个空格,空格用"*"代替
name = "Eric"
result = name.center(20,"*")
print(result)

#右边空出20个空格
name = "eric"
result = name.rjust(20)
print(result)

#左右空出20个空格
name = "eric"
result = name.ljust(20)
print(result)

#统计字符串里某个字符出现个数,可定义索引开始和结束位置
name = "sdfsrhshdkfk"
result = name.count("sh",5,10)
print(result)

#转换编码
name = "李连"
result = name.encode("gbk")
print(result)

#查找字符串里包含某个字符,可定义索引开始和结束为止
name = 'alex'
result = name.endswith('e',0,3)
print(result)

#table转空格
name = 'a   lex'
result = name.expandtabs()
print(result)

#查找字符串内容,返回个数,如果没有返回负数
name = "alex"
#result = name.find("x")
print(result)

#查找字符串内容,返回个数,如果没有报错
name = "alex"
result = name.index("x")
print(result)

#格式化字符串,和%s类似
name = "{0} as {1}"
resutl = name.format('alaex','sb')
print(resutl)
name = "alex {name} as {id}"
result = name.format(name="sb",id="eric")
print(result)

#拼接字符串
li = ["s","b","a","l","e","x"]
result = "_".join(li)
print(result)

#大写转小写
name = "SLDKFSLDF"
result = name.lower()
print(result)

#小写转大写
name = "SLDKFSLDF"
result = name.upper()
print(result)

#所有大小写转换
name = "  SLDKFSLDF "
result = name.swapcase()
print(result)

#所有单词的首字母大写
name = "luo alex"
result = name.title()
print(result)

#去掉空格
name = "  SLDKFSLDF "
result = name.strip()
print(result)

#去掉左边空格
name = "  SLDKFSLDF "
result = name.lstrip()
print(result)

#去掉右边空格
name = "  SLDKFSLDF "
result = name.rstrip()
print(result)

#按字符串分割(不丢弃分隔符)
name = "alexissb"
result = name.partition("is")
print(result)

#按字符串分割(丢弃分隔符)
name = "alexissb"
result = name.split("is")
print(result)

在每行前面添加换行符
name = """
alex
is
sb"""
result = name.splitlines()
print(result)

#替换,转换前2个
name = "aalexisasb"
result = name.replace("a","o",2)
print(result)
View Code

 

dict 

 1 """
 2 dict内部功能
 3 """
 4 
 5 #清空字典
 6 dict = {'k1','k2'}
 7 print(dict.clear())
 8 
 9 #浅拷贝
10 dict = {'k1','k2'}
11 dict2 = dict.copy()
12 print(dict2)
13 
14 #深拷贝
15 import copy
16 dict = {'k1','k2'}
17 dict2 = copy.deepcopy(dict)
18 print(dict2)
19 
20 #指定字典key,并设置一个默认值,重新生成一个新的字典
21 dict = {'k1':'v1','k2':'v2'}
22 dict2 = dict.fromkeys(['k1','k2','k3'],'www')
23 print(dict2)
24 
25 #获取字典key值value,key不存在返回"None",(可指定默认参数,当key不存在返回默认值)
26 dict = {'k1':'v1','k2':'v2'}
27 dict2 = dict.get("k4",'eric')
28 print(dict2)
29 
30 ##获取字典的键值对,返回一个可迭代对象
31 dict = {'k1':'v1','k2':'v2'}
32 #获取key
33 for n in dict.keys():
34     print(n)
35 #获取valus
36 for i in dict.values():
37     print(i)
38 #items可以同时获取key和valus
39 for k,v in dict.items():
40     print(k,v)
41 
42 #移除一个指定的键值(因dict和list不一样,dict是有序的,必须要指定一个key)
43 dict = {'k1':'v1','k2':'v2'}
44 result = dict.pop('k1')
45 print(result)
46 
47 #随机移除一对键值
48 dict = {'k1':'v1','k2':'v2','k3':"v3"}
49 result = dict.popitem()
50 print(result)
51 
52 #给dict的key设置一个默认值
53 dict = {}
54 dict.setdefault("k2")
55 #相等于
56 dict["k2"] = "None"
57 print(dict)
58 
59 #更新字典
60 dict = {'k1':'v1','k2':'v2'}
61 dict.update({'k3':'eric','k4':'alex'})
62 print(dict)
View Code

 

list 

 1 """
 2 list内部功能
 3 """
 4 
 5 #列表尾部添加内容
 6 li = []
 7 li.append("aaaaaa")
 8 print(li)
 9 
10 #列表清空
11 li = ["a","b"]
12 li.clear()
13 print(li)
14 
15 #浅拷贝(只拷贝第一层)
16 li = ["a","b"]
17 a_li = li.copy()
18 print(a_li)
19 
20 #深拷贝(完整拷贝)
21 import copy
22 li = ["a","b"]
23 a_li = copy.deepcopy(li)
24 print(a_li)
25 
26 #统计字符
27 li = ["a","b","a","b","c"]
28 result = li.count("a")
29 print(result)
30 
31 #合并列表
32 aList = [123, 'xyz', 'zara', 'abc', 123]
33 bList = [2009, 'manni']
34 aList.extend(bList)
35 print(aList)
36 
37 #按索引位置插入字符
38 li = ["a","b","a","b","c"]
39 li.insert(0,"eric")
40 print(li)
41 
42 #默认移除最后一个元素(pop(1)可删除指定索引下标位置的内容)
43 li = ["a","b","a","b","c"]
44 li.pop()
45 print(li)
46 
47 #移除第一个指定元素
48 li = ["a","b","a","b","c"]
49 li.remove("a")
50 print(li)
51 
52 #反转
53 li = ["a","b","a","b","c"]
54 li.reverse()
55 print(li)
View Code

 

tuple 

 1 #coding:utf-8
 2 """
 3 tuple内部功能
 4 """
 5 
 6 #统计元组中的元素
 7 tup = (1,2,3,4,1,1,2,4)
 8 result = tup.count(1)
 9 print(result)
10 
11 #获取元组中指定元素的索引下标位置
12 tup = (1,2,3,4,1,1,2,4)
13 result = tup.index(4)
14 print(result)
View Code

 

set

 1 #coding:utf-8
 2 '''
 3 集合内部功能
 4 '''
 5 
 6 #添加元素
 7 s1 = set()
 8 s1.add('alex')
 9 s1.add('eric')
10 print(s1)
11 
12 #清除数据
13 s1 = set()
14 s1.add('alex')
15 s1.add('eric')
16 s1.clear() 
17 print(s1)
18 
19 #set会自动去重
20 s1 = set(['alex','eric','lisa','tim','alex'])
21 print(s1)   #{'alex','eric','lisa','tim'}
22 
23 #浅copy
24 s1 = set()
25 s1.add('alex')
26 s2 = s1.copy()
27 print(s2)
28 
29 #深copy
30 import copy
31 s1 = set()
32 s1.add('alex')
33 s2 = copy.copy(s1)
34 print(s2)
35 
36 
37 #随机移除一个数据(可用变量接收被移除的数据)
38 s1 = set(['alex','eric','lisa','tim'])
39 s2 = s1.pop()
40 print("s1:%s \ns2:%s"%(s1,s2))
41 
42 #指定一个移除的数据(返回修改原来set)
43 s1 = set(['alex','eric','lisa','tim'])
44 s1.remove("alex")
45 print(s1)
46 
47 #取差集,第一个set对比第二个set是否有重复数据,返回一个新的set对象
48 s1 = set(['alex','eric','lisa','tim','alex'])
49 s2 = s1.difference(['alex','eric'])
50 print(s1)
51 print(s2)
52 
53 #取差集修改操作,返回修改原来set
54 s1 = set(['alex','eric','lisa','tim','alex'])
55 s1.difference_update(['alex','eric'])
56 print(s1)
57 
58 #差集,比较两个set中共同不相同的数据(返回一个新的set)
59 s1 = set(['alex','eric','lisa','tim','alex'])
60 s2 = set(['alex','eric'])
61 result = s1.symmetric_difference(s2)  #{'lisa', 'tim'}
62 print(result)
63 
64 #取交集(获取两个set中重复的数据),并创建一个新的set
65 s1 = set(['alex','eric','lisa','tim','alex'])
66 s2 = set(['alex','eric'])
67 result = s1.intersection(s2)
68 print(result)   #{'alex', 'eric'}
69 
70 #取交集修改操作(获取两个set中重复的数据),修改原来set
71 s1 = set(['alex','eric','lisa','tim','alex'])
72 s2 = set(['alex','eric'])
73 s1.intersection_update(s2)
74 print(s1)   #{'alex', 'eric'}
75 
76 #判断两个set是否有交集,有返回False,没有True
77 s1 = set(['alex','eric','lisa','tim','alex'])
78 s2 = set(['alex','eric'])
79 print(s1.isdisjoint(s2))
80 print(s1)
View Code

 

counter

 1 #coding:utf-8
 2 '''
 3 计数器
 4 '''
 5 
 6 
 7 #Counter是对字典类型的补充,用于追踪值的出现次数(具备dict所有功能和自己的功能)
 8 import collections
 9 
10 #统计各字符出现的次数
11 obj = collections.Counter("sdflsjdlfksd")
12 print(obj)
13 print(obj)  #Counter({'s': 3, 'd': 3, 'f': 2, 'l': 2, 'k': 1, 'j': 1})
14 
15 #获取计数器的前几(4)位内容
16 ret = obj.most_common(4)
17 print(ret)
18 
19 #获取计数器的值(因为它是collections.Counter类型无法直接取值)
20 print(type(obj))
21 #利用items获取key,valu
22 for k,v in obj.items():
23     print(k,v)
24 #利用elements获取所有元素
25 for i in obj.elements():
26     print(i)
27 
28 #增加数据,然后统计
29 obj = collections.Counter([11,22,33])
30 print(obj)
31 obj.update(['tim',11,22])
32 print(obj)
33 
34 #删除数据,然后统计
35 obj.subtract(['tim',11,22])
36 print(obj)
View Code

 

orderedDict

 1 #coding:utf-8
 2 '''
 3 有序字典
 4 
 5 说明:
 6 有序字典类似于把dict的key放到list里面(因list是有序的)
 7 循环list,有序把值取出来,在对应dict的key取vlaus
 8 
 9 dict = {'k1':'v1','k2':'v2'...}
10 list = [k1,k2...]
11 for k in list:
12     print(dict[k])
13 '''
14 
15 from collections import OrderedDict
16 
17 #创建有序字典
18 dic = OrderedDict()
19 dic["k1"] = "v1"
20 dic["k2"] = "v2"
21 dic["k3"] = "v3"
22 print(dic)
23 
24 
25 #指定key删除(pop有返回值)
26 result = dic.pop("k1")
27 print(dic)
28 print(result)
29 
30 #删除退后一项
31 dic.popitem()
32 print(dic)
33 
34 
35 #设置OrderedDict默认值("k4","valu可以不指定为None")
36 dic.setdefault("k4","v4")
37 print(dic)
38 
39 #增加数据(传入一个新dict,增加到原来OrderedDict里面)
40 dic.update({"k5":"v5"})
41 print(dic)
42 
43 #把某一个key放到OrderedDict最后面
44 dic.move_to_end("k3")
45 print(dic)
View Code

 

defaultdict

 1 #coding:utf-8
 2 '''
 3 默认字典
 4 
 5 如果没有默认字典,需要自己定义一个value的默认类型为list的字典:
 6 dic = {"name":[]}
 7 dic["name"].append("alex")
 8 dic["name"].append("eric")
 9 print(dic)
10 
11 下面通过collections.defaultdict()快速创建默认字典类型
12 '''
13 
14 import collections
15 #类型为list
16 dic = collections.defaultdict(list)
17 dic["name"].append("alex")
18 dic["name"].append("eric")
19 print(dic)  #defaultdict(<class 'list'>, {'name': ['alex', 'eric']})
20 
21 from collections import defaultdict
22 li = [11,22,33,44,55,66,77,88,99,90]
23 dic = defaultdict(list)
24 for n in li:
25     if n >66:
26         dic["k1"].append(n)
27     elif n <= 66:
28         dic['k2'].append(n)
29 print(dic)
View Code

 

namedtuple

 1 #coding:utf-8
 2 '''
 3 可命名元祖
 4 
 5 根据nametuple可以创建一个包含tuple所有功能以及其他功能的类型
 6 类似给元组value创建一个别名
 7 '''
 8 
 9 import collections
10 
11 #创建类
12 MytupleClass = collections.namedtuple("MytupleClass",{'x','y','z'})
13 print(MytupleClass)
14 #创建类属性的别名
15 obj = MytupleClass(11,22,33)
16 print(obj.x)
17 print(obj.y)
18 print(obj.z)
19 
20 #可查看这个类的方法属性
21 print(help(MytupleClass))
View Code

 

deque

 1 #coding:utf-8
 2 '''
 3 双向队列
 4 
 5 说明:
 6 类似于RabbitMQ的消息队列
 7 '''
 8 
 9 import collections
10 
11 #创建一个双向队列
12 d = collections.deque()
13 print(d)
14 
15 #往队列最后面添加一个value
16 d.append('pp')
17 d.append('aa')
18 d.append({1:111})
19 print(d)
20 
21 #往队列最左边添加一个value
22 d.appendleft('aa')
23 print(d)
24 
25 #清空这个队列
26 d.clear()
27 print(d)
28 
29 #队列计数器(统计”aa“有多少个)
30 count = d.count('aa')
31 print(count)
32 
33 #右扩展(在队列的右边添加多个元素)
34 d.extend(['bb','cc','dd'])
35 print(d)
36 #d.extend({2:222})   #拓展不要添加字典(只会把字典key加入拓展,而value不会加入)
37 
38 #左拓展(在队列的左边添加多个元素)
39 d.extendleft([1,2,3])
40 print(d)
41 
42 #取一个值的索引位置(有多个值,按照从左到右显示第一个)
43 print(d.index("aa"))
44 
45 #在某位置插入值
46 d.insert(2,"insert")
47 print(d)
48 
49 #移除一个value(从右边开始)
50 result = d.pop()
51 print(d)
52 print(result)
53 
54 #移除一个value(从左边开始)
55 result = d.popleft()
56 print(d)
57 print(result)
58 
59 #移除某些指定的value(如果有重复的值,按照从左到右的顺序移除)
60 d.remove("insert")
61 d.remove("aa")
62 print(d)
63 
64 #反转排列顺序
65 d.reverse()
66 print(d)
67 
68 #转圈圈,把最后value放到最前(可指定需要把多少个value旋转到最前面)
69 d.rotate(2)
70 print(d)
View Code

 

queue.queue

 1 #coding:utf-8
 2 '''
 3 单向队列
 4 
 5 说明:
 6 类似于RabbitMQ的消息队列
 7 '''
 8 
 9 import queue
10 
11 #创建单向队列
12 q = queue.Queue()
13 
14 
15 #插入一条数据
16 q.put("123")
17 q.put("456")
18 
19 #查看队列个数
20 print(q.qsize())
21 
22 #取一条数据
23 print(q.get())
View Code

 

copy

 1 #coding:utf-8
 2 
 3 import copy
 4 
 5 #浅拷贝
 6 #copy.copy()
 7 #深拷贝
 8 #copy.deepcopy()
 9 
10 
11 
12 # 浅拷贝:只复制最外面一层
13 dic = {
14     "cpu":[80],
15     "mcm":[80],
16     "disk":[80]
17        }
18 
19 print("brefor %s"%dic)
20 new_dic = copy.copy(dic)
21 dic["cpu"][0] = 50
22 print(dic)
23 print(new_dic)
24 
25 
26 # 深拷贝:新开辟一个内存存储复制的内容,和原来的数据互不影响
27 dic = {
28     "cpu":[80],
29     "mcm":[80],
30     "disk":[80]
31        }
32 
33 print("brefor %s"%dic)
34 new_dic = copy.copy(dic)
35 #new_dic["cpu"][0] = 50
36 dic["cpu"][0] = 50
37 print(dic)
38 print(new_dic)
View Code

 

posted @ 2017-04-26 15:12  矜持小蝌蚪  阅读(254)  评论(0编辑  收藏  举报
levels of contents