python学习记录(三)-数据类型

字符串格式化

var = 'abcde'
# 切片
print(var[2],var[-1]) # c e
print(var[1:3:1],var[-2:-5:-1],var[::-1]) # bc dcb edcba
# 单元素赋值
#var[2] = '1' # TypeError: 'str' object does not support item assignment
# 格式化
var1 = '{},welcome to {}'.format('osan','china')
var2 = '{2},welcome to {1}'.format('osan','china','misaki')
var3= '{a},welcome to {b}'.format(a='osan',b='china')
var4= '{0[2]},welcome to {0[1]}'.format(['osan','china','misaki'])
data = {'a':'osan','b':'china'}
var5 = '{a},welcome to {b}'.format(**data)
print(var1) # osan,welcome to china
print(var2) # misaki,welcome to china
print(var3) # osan,welcome to china
print(var4) # misaki,welcome to china
print(var5) # osan,welcome to china
# 特殊用法-保留小数位
var = '{:.4f}'.format(3.1415926)
print(var) # 3.1416

字符串检测

vars = 'kuroko'
print(vars.capitalize()) # Kuroko 首字母大写
vars = 'siroi kuroko'
print(vars.title()) # Siroi Kuroko 标题格式(每个单词的首字母大写)
print(vars.upper()) # SIROI KUROKO 大写
print(vars.upper().lower()) # siroi kuroko 小写
vars = 'ZeroTsu'
print(vars.swapcase()) # zEROtSU 大小写转换
print(vars.isupper(),vars.upper().isupper()) # False True 是否大写
print(vars.islower(),vars.lower().islower()) # False True 是否小写
vars = 'fate staynight'
print(vars.istitle(),vars.title().istitle()) # False True 是否标题格式
vars2 = 'fatestaynight2020'
print(vars.isalnum(),vars2.isalnum()) # False True 是否由(中文/英文字符/数字字符)组成
vars3 = 'keiyakusya'
print(vars2.isalpha(),vars3.isalpha()) # False True 是否由(英文字符)组成
var4 = '2020'
print(vars3.isdigit(),var4.isdigit()) # 是否由(数字字符)组成 False True
vars5 = ' '
print(vars.isspace(),vars5.isspace()) # 是否由(空格)组成 False True
print(vars3.startswith('ke'),vars3.startswith('ku',5)) # 是否以ke开头 True True
print(vars3.endswith('sya'),vars3.endswith('ku',0,7)) # 是否以sya结尾 True True

字符串查找

vars3 = 'keiyakusya'
print(vars3.find('k',0,6),vars3.rfind('k',0,6),vars3.find('b')) # 0 5 -1
print(vars3.index('k',0,6),vars3.rindex('k',0,6)) # 0 5
#print(vars3.index('b')) ValueError: substring not found
print(vars3.count('k')) # 2

字符串操作

# 分尸
vars = 'userid=000000&type=admin&sex=f'
res = vars.split('&')
print(res) # ['userid=000000', 'type=admin', 'sex=f']
for i in res:
    a = i.split('=')
    print(a) # ['userid', '000000'] ['type', 'admin'] ['sex', 'f']
# 接上
print(','.join(res)) # userid=000000,type=admin,sex=f
# 花式分尸
print(vars.split('&',1)) # ['userid=000000', 'type=admin&sex=f']
print(vars.rsplit('&',1)) # ['userid=000000&type=admin', 'sex=f']
# 去两端字符
vars = '**去除**星号***'
print(vars.strip('*')) # 去除**星号
print(vars.lstrip('*')) # 去除**星号***
print(vars.rstrip('*')) # **去除**星号
# 替换
vars = '替换abcabcabc'
print(vars.replace('a','A')) # 替换AbcAbcAbc
print(vars.replace('a','A',2)) # 替换AbcAbcabc
# 填充
vars = '对称填充'
print(vars.center(12,'*')) # ****对称填充****
print(vars.center(13,'*')) # *****对称填充****
vars = '填充'
print(vars.ljust(6,'*')) # 填充****
print(vars.rjust(6,'*')) # ****填充

列表基本操作

varlist1 = [1,2,3]
varlist2 = ['a','b','c']
print(varlist1+varlist2) # [1, 2, 3, 'a', 'b', 'c'] 拼接
print(varlist1*2) # [1, 2, 3, 1, 2, 3] 重复
print('a' in varlist2) # True 是否包含
# varlist1[3] = 4 IndexError: list assignment index out of range
varlist1.append(4) # 添加
print(varlist1,len(varlist1)) # [1,2,3,4] 4
del varlist1[3] # 指定删除
print(varlist1,len(varlist1)) # [1,2,3] 3
print(varlist1.pop(),varlist1) # 3 [1, 2] 最后一个删除

列表切片

varlist = ['列','表','切','片','操','作']
print(varlist) # ['列', '表', '切', '片', '操', '作']
varlist[1:3] = '23'
print(varlist) # ['列', '2', '3', '片', '操', '作']
varlist[1:3] = 'b'
print(varlist) # ['列', 'b', '片', '操', '作']
varlist[1:3] = '234'
print(varlist) # ['列', '2', '3', '4', '操', '作']

列表相关函数

varlist = ['a','b','c','a','f','g']
print(len(varlist),varlist.count('a')) # 6 2 长度,某个字符在列表中出现的次数
varlist.insert(0,'aa') # 指定位置添加
varlist.append('gg') # 在最后添加
print(varlist) # ['aa', 'a', 'b', 'c', 'a', 'f', 'g', 'gg']
res = varlist.pop() # 弹出最后一个元素
print(res,varlist) # gg ['aa', 'a', 'b', 'c', 'a', 'f', 'g']
res = varlist.pop(0) # 弹出指定位置的元素
print(res,varlist) # aa ['a', 'b', 'c', 'a', 'f', 'g']
res = varlist.remove('a') # 删除指定元素 
print(res,varlist) # None ['b', 'c', 'a', 'f', 'g']
print(varlist.index('a'),varlist.index('a',1,4)) # 2 2 元素在列表中的索引
varlist.extend('扩展元素') # 作为多个元素添加
print(varlist) # ['b', 'c', 'a', 'f', 'g', '扩', '展', '元', '素']
varlist.reverse() # 列表内容倒过来
print(varlist) # ['素', '元', '展', '扩', 'g', 'f', 'a', 'c', 'b']
varlist.clear() # 清空
print(varlist) # []
# 排序
varlist = [5,2,1,8,-3,6]
varlist.sort()
print(varlist) # [-3, 1, 2, 5, 6, 8]
varlist.sort(reverse=True,key=abs)
print(varlist) # [8, 6, 5, -3, 2, 1]
# 拷贝
varlist1 = ['a','b','c',[1,2]]
varlist2 = varlist1.copy()
print(varlist1,varlist2) # ['a', 'b', 'c', [1, 2]] ['a', 'b', 'c', [1, 2]]
del varlist2[2]
print(varlist1,varlist2) # ['a', 'b', 'c', [1, 2]] ['a', 'b', [1, 2]]
del varlist2[2][0]
print(varlist1,varlist2) # ['a', 'b', 'c', [2]] ['a', 'b', [2]]

列表的深拷贝与浅拷贝

#浅拷贝
varlist1 = [1,2,3,4]
varlist2 = varlist1.copy()
del varlist2[3]
print(varlist1,id(varlist1)) # [1, 2, 3, 4] 2235588760072
print(varlist2,id(varlist2)) # [1, 2, 3] 2235588760584
varlist1 = [1,2,['a','b','c']]
varlist2 = varlist1.copy()
del varlist2[2][2]
print(varlist1,id(varlist1[2])) # [1, 2, ['a', 'b']] 1962166488968
print(varlist2,id(varlist2[2])) # [1, 2, ['a', 'b']] 1962166488968
#深拷贝
import copy
varlist1 = [1,2,['a','b','c']]
varlist2 = copy.deepcopy(varlist1)
del varlist2[2][2]
print(varlist1,id(varlist1[2])) # [1, 2, ['a', 'b', 'c']] 1725185913224
print(varlist2,id(varlist2[2])) # [1, 2, ['a', 'b']] 1725185915784

列表推导式

varlist = [i**2 for i in range(5)]
print(varlist) # [0, 1, 4, 9, 16]
varlist = [i for i in range(10) if i % 2 == 0]
print(varlist) # [0, 2, 4, 6, 8]

元组推导式

varlist = [1,2,3,4]
res = (i**2 for i in varlist)
print(res,type(res)) # <generator object <genexpr>> <class 'generator'>
print(next(res)) # 1
print(list(res)) # [4,9,16]

yield关键字

def fun():
    print('一')
    yield 1
    print('二')
    yield 2
    print('三')
    yield 3
    print('四')
    yield 4

res = fun()
print(res,type(res)) # <generator object fun> <class 'generator'>
print(next(res)) # 一\n 1\n
print(next(res)) # 二\n 2\n
print(list(res)) # 三\n 四\n [3,4]

字典的定义

vardict = {'a':1,'b':2}
print(vardict) # {'a': 1, 'b': 2}
vardict = dict([['a',1],['b',2]])
print(vardict) # {'a': 1, 'b': 2}
vardict1 = ['a','b']
vardict2 = [1,2] 
print(dict(zip(vardict1,vardict2))) # {'a': 1, 'b': 2}

字典的基本操作

var1 = {'a':1,'b':2}
var2 = {'c':3,'d':4}
#print(var1 + var2) TypeError: unsupported operand type(s) for +: 'dict' and 'dict' 不能连接
#print(var1 * 2) TypeError: unsupported operand type(s) for *: 'dict' and 'int' 不能重复
print(var1['a']) # 1 取值
var1['a'] = 11 # 赋值
print(var1) # {'a': 11, 'b': 2}
var1['aa'] = 111 # 添加
print(var1) # {'a': 11, 'b': 2, 'aa': 111}
var1['aa'] = 222
print(var1) # {'a': 11, 'b': 2, 'aa': 222}
del var1['aa'] # 删除
print(var1) # {'a': 11, 'b': 2}
print('aa' in var1,'aa' not in var1) # False True 是否存在
print(var1.keys()) # dict_keys(['a', 'b']) 取出key 
print(var1.values()) # dict_values([11, 2]) 取出值
print(var1.items()) # dict_items([('a', 11), ('b', 2)]) 取出key和值
for i in var1:
    print(i,var1[i]) # a 11\n b 2
for k,v in var1.items():
    print(k,v) # a 11\n b 2

字典的相关函数

vardict = {'a':1,'b':2,'c':3}
res = iter(vardict) # 转换成迭代器
print(res,type(res)) # <dict_keyiterator object> <class 'dict_keyiterator'>
res = vardict.pop('a') # 指定key弹出
print(res,vardict) # 1 {'b': 2, 'c': 3}
res = vardict.popitem() # 弹出最后一个
print(res,vardict) # ('c', 3) {'b': 2}
print(vardict.get('b'),vardict.get('c')) # 2 None 按key取值
#print(vardict['c']) KeyError: 'c'
res = vardict.get('c',3)
print(res,vardict) # 3 {'b': 2}
# 添加
vardict.update(b=22)
vardict.update({'a':1,'c':3})
print(vardict) # {'b': 22, 'a': 1, 'c': 3}
# 设置默认值
print(vardict.setdefault('b'),vardict) # 22 {'b': 22, 'a': 1, 'c': 3}
print(vardict.setdefault('d'),vardict) # None {'b': 22, 'a': 1, 'c': 3, 'd': None}
print(vardict.setdefault('e',4),vardict) # 4 {'b': 22, 'a': 1, 'c': 3, 'd': None, 'e': 4}

字典推导式

vardict = {'a':1,'b':2}
res = {v:k for k,v in vardict.items()}
print(res) # {1: 'a', 2: 'b'}

集合的基本操作

var = {1,2,3}
# 添加
var.add(4)
print(var) # {1,2,3,4}
var.update([3,5,6])
print(var) # {1,2,3,4,5,6}
# 删除
#var.pop() 随机删
var.remove(4)
print(var) # {1,2,3,5,6}
#var.remove('a') KeyError: 'a'
var.discard('a')
print(var) # {1,2,3,5,6}
# 拷贝
var2 = var.copy()
print(var2) # {1,2,3,5,6}
# 清空
var.clear()
print(var) # set()

冰冻集合

var = frozenset([1,2,3])
print(var,type(var)) # frozenset({1, 2, 3}) <class 'frozenset'>
# 推导式
var = frozenset({i<<2 for i in range(6)})
print(var) # frozenset({0, 16, 4, 20, 8, 12})
# 拷贝
var2 = var.copy()
print(var2) # frozenset({0, 16, 4, 20, 8, 12})
集合运算
var1 = {'a','b','1','2'}
var2 = {'1','2','c','d'}
# 交集
print(var1 & var2) # {'2', '1'}
print(var1.intersection(var2)) # {'2', '1'}
res = var1.intersection_update(var2)
print(res,var1) # None {'1', '2'}
# 并集
print(var1 | var2) # {'1', 'c', 'd', '2', 'a', 'b'}
print(var1.union(var2)) # {'1', 'c', 'd', '2', 'a', 'b'}
res = var1.update(var2)
print(res,var1) # None {'1', 'c', 'd', '2', 'a', 'b'}
# 差集
print(var1 - var2,var2 - var1) # {'b', 'a'} {'c', 'd'}
print(var1.difference(var2)) # {'b', 'a'}
res = var1.difference_update(var2)
print(res,var1) # None {'a', 'b'}
# 对称差集
print(var1 ^ var2) # {'d', 'c', 'a', 'b'}
print(var1.symmetric_difference(var2)) # {'d', 'c', 'a', 'b'}
res = var1.symmetric_difference_update(var2)
print(res,var1) # None {'d', 'c', 'b', 'a'}
# 超集、子集
var1 = {1,2,3,4,5,6}
var2 = {1,2,3,4}
print(var1.issuperset(var2),var2.issubset(var1)) # True True
# 是否不相交
print(var1.isdisjoint(var2)) # False
上一篇:Python中的深拷贝和浅拷贝


下一篇:iTunes Converter for mac(音频格式转换工具)