基础数据类型汇总:
#!/usr/bin/env python # -*- coding:utf-8 -*- ''' str int ''' # str s = ' a' print(s.isspace()) ''' list: ''' li_st = [11, 22, 33, 44, 55] for i in range(len(li_st)): # range()也是顾头不顾尾 del li_st[i] #del操作会更新列表 删掉所有偶数 for i in li_st: if i % 2 == 0: del li_st[li_st.index(i)] print(li_st) dic = {'k1': 'v1', 'k2': 'v2', 'a3': 'v3'} dic1 = {} #循环字典过程中,不能删除字典的键值对; for i in dic: if 'k' in i: del dic[i] for i in dic: if 'k' not in i: dic1.setdefault(i, dic[i]) dic = dic1 print(dic) l = [] for i in dic: if 'k' in i: l.append(i) for i in l: del dic[i] print(dic) # 转换成bool是false: # 0 '' [] () {} set() # 元组 如果元组里面只有一个元素且不加 逗号, 则此元素是什么类型,就是什么类型 tu1 = (1) tu2 = (1,) print(tu1,type(tu1)) print(tu2,type(tu2))
集合:
#!/usr/bin/env python # -*- coding:utf-8 -*- ''' 集合: 可变的数据类型;可以增删改查 储存元素必须是不可变的数据类型 无序,不重复, {} ''' set1 = set({1, 2, 3}) set2 = {1, 2, 3, [1, 2, 3], {'name': 'alex'}} #报错,集合中的元素必须是可哈希的 print(set1) print(set2) set1 = {'alex', 'wusir', 'ritian', 'egon', 'barry', 'barry'} # 集合建立时可以重复元素,会在建立过程中自动去重操作 # 增 # add set1.add('godress') print(set1) update set1.update('abc') print(set1) # 删 # pop 随机删除,集合为空的时候报错 name = set1.pop( ) print(name) print(set1) # remove 按元素删除,元素不存在报错 set1.remove('barry') print(set1) # 清空列表 set1.clear() print(set1) # del 删除整个集合 del set1 print(set1) # 查 # 只能用for循环查询 for i in set1: print(i) # 集合运算 set1 = {1, 2, 3, 4, 5} set2 = {4, 5, 6, 7, 8} set3 = set1 & set2 # 交集 print(set1 & set2) print(set1.intersection(set2)) # 反交集 print(set1 ^ set2) print(set1.symmetric_difference(set2)) # 并集 print(set1 | set2) print(set1.union(set2)) # 差集 print(set1 - set2) print(set1.difference(set2)) # 子集 set4 = {1, 2} set5 = {1, 2, 3} print(set4 < set5) print(set4.issubset(set5)) # 超集 set4 = {1, 2} set5 = {1, 2, 3} print(set5 > set4) print(set5.issuperset(set4)) # 将集合变为不可变数据类型,即只读集合 s = frozenset('barry') print(s, type(s)) # 只能查询 for i in s: print(i)
深浅拷贝:
#!/usr/bin/env python # -*- coding:utf-8 -*- # 赋值 # l1 = [1, 2, 3, ['a', 'b', 'c']] # l2 = l1 # print('original L1:', l1) # print('original L2:', l2) # # l2[3][0] = 'k' # print('changed L2:', l2) # print('changed L1:', l1) # 因为赋值操作是直接把两个变量(L1,L2)同时指向同一个内存地址,所以动一发而牵全身 # 浅拷贝 # l1 = [1, 2, 3, ['a', 'b', 'c']] # l2 = l1.copy() # print('original L1:', l1) # print('original L2:', l2) # # l2[0] = 4 # l2[3][1] = 'k' # print('changed L2:', l2) # print('changed L1:', l1) # 浅拷贝:将拷贝对象的值拷贝到另一个内存地址,但是拷贝对象的子代仍是和原来指向同一个内存地址 # 深拷贝 # import copy # l1 = [1, 2, 3, ['a', 'b', 'c']] # l2 = copy.deepcopy(l1) # print('original L1:', l1) # print('original L2:', l2) # l2[0] = 4 # l2[3][1] = 'k' # print('changed L2:', l2) # print('changed L1:', l1) # print(l2 is l1) # 深拷贝,将拷贝对象的值全部重新拷贝到新的内存地址里