Python(7): 数据类型的常用操作-- 集合的常用方法(待写)

字符串的常用方法

 

 

 

 

 

 

代码示例:

"""
字符串的操作
"""
# 首字母大写的方法
str = 'dawei xiaoming'
info = 'hello 小明'
num_str = '1314'

newstr = str.capitalize()
new_info = info.capitalize()
new_num_str = num_str.capitalize()
print(newstr)
print(new_info)
print(new_num_str)

# 字符串全部小写的方法lower()/casefold() 这两个方法几乎一致,lower()只对英文有效,casefold()可对其他语种有效
message_en = 'How do you do? XiaoMing'
message_ch = '你好呀,XiaoMing'
message_mix = '你好呀,XiaoMing,今天星期3!'

message_en_lower = message_en.lower()
message_en_casefold = message_en.casefold()

message_ch_lower = message_ch.lower()
message_ch_casefold = message_ch.casefold()

message_mix_lower = message_mix.lower()
message_mix_casefold = message_mix.casefold()

print( message_en_lower, message_en_casefold )
print( message_ch_lower, message_ch_casefold )
print( message_mix_lower, message_mix_casefold )

# 字符串全部大写的方法upper()
info = 'hello word! hello xiaoming'

big_info = info.upper()
small_info = info.lower()

print(big_info)
print(small_info)

# 字符串中大小写字母进行转换的方法swapcase()
info_one = 'Python Code Is Good'
info_two = 'PYTHON DJANGO FLASK'
info_three = 'python web so easy'

info_one_new = info_one.swapcase()
info_two_new = info_two.swapcase()
info_three_new = info_three.swapcase()

print(info_one_new)
print(info_two_new)
print(info_three_new)

# 字符串zfill()填充方法
info = 'love'

print(' t   ' + info)
print('t    ' + info)
print(info.zfill(10))
print(info.zfill(9))
print(info.zfill(8))
print(info.zfill(6))
print(info.zfill(4))


# 字符串中成员的个数count()方法
info = """
Python now uses the same ABI whether it's built in release or debug mode.on Unix,when Python is built in debug mode,
it is now possible to load cextensions built in release mode and c extensions built using the stableABI.

"""
a = info.count('a')
b = info.count('b')
c = info.count('c')
d = info.count('d')
e = info.count('e')


print(a,b,c,d,e)
num_list = [a,b,c,d,e]
print('在列表中最大的数值是:', max(num_list))

num_dict = {
    'a':a,
    'b':b,
    'c':c,
    'd':d,
    'e':e
}
print( '每个成员对应的数值是:',num_dict )


# 判断字符串开始位和结尾的方法startswith()/endswith()
info = 'this is a string example!!'

print('字符串开始位匹配:',info.startswith('this'))
print('字符串完全匹配:',bool(info == 'this is a string example!!'))

print('字符串结尾匹配:',info.endswith('!'))
print('字符串结尾匹配:',info.endswith('this'))

# 获取字符串中某个值的位置方法find()和index()方法
info = 'python is a good code'

print(info.find('a'))
print(info.find('ok'))  # find()方法找不到该元素位置时,返回-1

print(info.index('a'))
print(info.index('ok'))  # index()方法找不到该元素位置时,程序报错


# 去除字符串左右两边的元素或空格的方法strip();lstrip():仅去掉字符串开头的指定元素或空格;

info_01 = '  my name is xiaoming  '
new_info_01 = info_01.strip()
print('.' + new_info_01 + '.')  # 去除字符串左右两边的空格

new_str = 'abcde'
print( new_str.strip('a') )  # 去除字符串左右两边的a元素
print( new_str.lstrip('a') )  # 去除字符串左边的a元素
print( new_str.rstrip('e') )  # 去除字符串右边的e元素


# 替换字符串中元素的方法replace()方法
info = """
要从小白到一个有经验的开发者,无论是通过视频还是文字教程学习,你会发现很少有初级课程就非常贴近实际工作的,
作为一个刚入坑的小白通常并不知道需要学习什么,往往是自认为入门的时候都学习了,到了公司里才发现很多都不会。
我希望做这样一个课程,虽是入门课程,但涉及相关领域的多处知识,让小白在学习后进入公司岗位不会因为没听过而蒙圈;
同时希望这个课也可以帮助非Python工程师怏速转型或者快速转职能)
"""
a = '小白'
b = '一个'
c = '蒙圈'
d = '课程'
e = '*'
f = '@'
g = '$'
h = '&'

new_str_01 = info.replace(a,e).replace(b,f).replace(c,g).replace(d,h)
print(new_str_01)

new_str = info.replace(a,e)
new_str = new_str.replace(b,f)
new_str = new_str.replace(c,g)
new_str = new_str.replace(d,h)
print(new_str)

# 字符串中返回bool类型的函数集合
title = 'Back Of China'
upper_str = 'PYTHON IS A GOOD CODE'
lower_str = 'i love python'
not_empty = ' '

# istitle() 判断字符串是否是一个标题类型(标题类型是字符串中每个首字母都是大写为标题类型)
print(title.istitle())
# isupper() 判断字符串中的字母是否都是大写
print(upper_str.isupper())
# islower() 判断字符串中的字母是否都是小写
print(lower_str.islower())
# isspace() 判断字符串是否是一个由空格组成的字符串
print(not_empty.isspace())

# 字符串格式化操作 %,format,f-string
str_01 = 'my name is %s,my age is %.2f'
print(str_01 % ('xiaoming',33))

str_02 = 'my name is {0},my age is {1}'
print(str_02.format('xiaobai',20))

name = 'xiaoxin'
age = 28
str_03 = f'my name is {name},my age is {age}'
print(str_03)

列表的常用方法

 

 

 

 

 

 

 

 

代码示例:

"""
列表的常用操作
"""
# 列表的添加append()函数
book_type = []
book_type.append('生活')
book_type.append('娱乐')
print(book_type)
# 通过append函数列表中可添加不同的数据类型
num_float = 3.1
tuple_test = ('新闻',)
dict_test = {'name':'xiaoming'}
book_type.append(num_float)
book_type.append(tuple_test)
book_type.append(dict_test)
print(book_type)

# 列表的添加insert()函数:将一个元素添加到当前列表的指定位置中
book_type_01 = [
    {'name':'xiaoming','age':18,'top':180},
    {'name':'xiaobai','age':20,'top':190}
]
name_01 = {'name':'xiaoxin', 'age':33, 'top':168}
book_type_01.insert(0,name_01)
print(book_type_01)

# 列表(元组)的count()函数--返回成员的个数

animals = ['小狗','小猫','小鸭','小狗','小猪','小鸡','小兔子','小猪','小马','小狗','小猫','小猪']
cat = animals.count('小猫')
dog = animals.count('小狗')
pig = animals.count('小猪')

print('list:' + '我家的院子里有很多小动物')
print('小狗有 %s 只' % dog)
print('小猫有 {0} 只'.format(cat))
print(f'小猪有 {pig} 只')
print('松鼠有 %s 只' % animals.count('松鼠'))
print('我家的院子里一共有小猫 %s 只\n小狗有 %s 只\n小猪有 %s 只\n松鼠有 %s 只' % (cat,dog,pig,animals.count('松鼠')))
print('==============================')
tuple_animals = ('小狗','小猫','小鸭','小狗','小猪','小鸡','小兔子','小猪','小马','小狗','小猫','小猪')
cat = animals.count('小猫')
dog = animals.count('小狗')
pig = animals.count('小猪')
print('tuple' + '我家的院子里有很多小动物')
print('list:' + '我家的院子里有很多小动物')
print('小狗有 %s 只' % dog)
print('小猫有 {0} 只'.format(cat))
print(f'小猪有 {pig} 只')
print('松鼠有 %s 只' % animals.count('松鼠'))
print('我家的院子里一共有小猫 %s 只\n小狗有 %s 只\n小猪有 %s 只\n松鼠有 %s 只' % (cat,dog,pig,animals.count('松鼠')))

# 删除元素的remove()函数;删除整个变量的内置函数del
shops = ['可乐','洗发水','牙膏','可乐','牛奶','牙膏','雪碧','矿泉水','牙膏']
print('超市里有:%s' % shops)
print('牛奶有 %s 件' % shops.count('牛奶'))
print('可乐有 %s 件' % shops.count('可乐'))
print('牙膏有 %s 件' % shops.count('牙膏'))
shops.remove('可乐')
print('现在可乐有 %s 件'% shops.count('可乐'))
shops.remove('可乐')
print('现在可乐有 %s 件'% shops.count('可乐'))

# del 删除整个变量
del shops
print(shops)

# 对当前列表顺序进行反转的reverse()函数
students = [
    {'name':'xiaoming','age':33,'top':170},
    {'name':'xiaoxin','age':22,'top':180},
    {'name':'xiaobai','age':11,'top':190}
]
print('当前学生的座位顺序是{}'.format(students))
students.reverse()
print('调整座位后的顺序是{}'.format(students))


# 按照一定规律进行排序的sort()函数; key:参数比较;reverse=True(降序),reverse=False(升序)默认
a = ['a','d','g','b','c','e','f']
b = [31,64,75,16,83,92,47]
a.sort()
b.sort()
print(a)
print(b)
shenxiao = ['03老虎','01老鼠','11狗','09猴子','02牛','05龙','07马','04兔子','08羊','10鸡','12猪','06蛇']
shenxiao.sort(reverse=True)
print(shenxiao)
shenxiao.sort(reverse=False)
print(shenxiao)

# 清空列表中的数据clear()函数
mixs = [ 'python',1,(2,),{'name':'xiaoming'} ]
print( mixs,len(mixs) )
mixs.clear()
print( mixs,len(mixs) )

# 列表的copy()函数;list.copy()   该函数无参数,返回一个一模一样的列表
# 浅拷贝: 有一个列表a,列表里的元素还是列表,当我们拷贝出新列表b后,无论是a,还是b的内部的列表中的数据发生了变化后,相互之间都会收到影响---浅拷贝
# 深拷贝: 不仅对第一层数据进行了copy,对深层的数据也进行copy,原始变量和新变量完完全全不共享数据---深拷贝
import copy

old_list = [['java'],'python','django','flask']
new_list = old_list.copy()
print(old_list, new_list)

new_list.append('golang')
print(old_list, new_list)
# 浅拷贝:列表中的列表元素发生变化,新老列表同样发生变化
old_list[0].append('php')
print(old_list, new_list)

# 深拷贝:列表中的列表元素发生变化,新老列表不会发生变化
old_list_01 = [['java'],'python','django','flask']
new_list_01 = copy.deepcopy(old_list_01)
new_list_01[0].append('js')
print( old_list_01, new_list_01 )

# 将其他列表或元组导入到当前列表中的extend()函数
list_one = []
list_two = []
list_three = []

books = ('生活','娱乐','新闻')
code = ['python','java','golang']
dict_students = {'name':'xiaoming','age':22,'top':180}

list_one.extend(books)
print(list_one)
list_two.extend(code)
print(list_two)
# 字典数据类型只会把key添加到列表中
list_three.extend(dict_students)
print(list_three)
# 把其他数据类型加入到列表中,并把该数据类型的变量删除
list_one.extend(dict_students)
del dict_students
print(list_one)
# 把字符串导入列表中,字符串会分割成单个字符串
list_one.extend('asdf')
print(list_one)

# 列表的索引和切片
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print('获取列表中的索引数',len(numbers)-1)
print('获取索引9的元素',numbers[9])
print('获取列表的完整数据',numbers[:])
print('另一种获取列表的完整数据',numbers[0:])
print('第三种获取列表的数据,除了最后一个元素',numbers[:-1])
print('列表的反序',numbers[::-1])
print('列表的反向获取',numbers[-3:-1])
print('步长获取切片',numbers[0:8:2])
print('步长生成空列表',numbers[0:0])
# 通过索引返回一个新的列表
new_numbers = numbers[0:5]
print(new_numbers)
# 通过索引,获取与修改
numbers_two = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
numbers_two[2] = 'a'
print(numbers_two)
numbers_two[3:6] = ['b','c','d']
print(numbers_two)

# 通过索引删除并返回删除的值 pop()函数
numbers_three = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
new_numbers_three = numbers_three.pop(2)
print(new_numbers_three, numbers_three)

# 通过del删除索引,无返回值
numbers_four = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
del numbers_four[0]
print(numbers_four)
# 通过del可以删除整个元组,但是不能对元组中的索引进行删除
tuple_num = (1,2,3)
del tuple_num[1]  # 报错TypeError
print(tuple_num)
del tuple_num  # 删除整个元组

 

字典的常用方法

 

 

 

 

 

代码示例:

"""
字典的常用操作
"""
# 字典的添加数据的方法;添加或修改,根据key是否存在所决定的
user = {'name':'xiaoming','age':20}
# key不存在,则是添加
user['top'] = 180
print(user)
# key存在,则是修改
user['name'] = 'xiaobai'
print(user)

# update()函数
students = {'name':'xiaoxin','age':20}
new_student = {'name':'xiaomu','age':18,'top':175,'sex':''}
students.update(new_student)
print(students)

# setdefault(key,value)函数;  该函数返回key的值
# 如果key在字典中存在,返回key的值
user = {'name':'xiaoming','age':20}
value = user.setdefault('name','xiaoyun')
print(user,value)
# 如果key在字典中不存在,则key和value的值添加到字典中
new_value = user.setdefault('birthday','2022-1-1')
print(user,new_value)

# 获取字典的所有keys()函数
mix_dict = {'id':1, 'project_name':'ipad', 'price':2000, 'count':30}
project_title = mix_dict.keys()
print(type(project_title))  # dict_keys 该类型是一个伪列表,不具备列表的所有功能
print(project_title[0])  # 报错 TypeError

# 通过list()函数定义封装成列表,则具备列表的所有功能
project_title_01 = list(mix_dict.keys())
print(project_title_01)
print(project_title_01[0])
project_title_01.append('top')
print(project_title_01)

# 获取字典的所有values()函数
mix_dict = {'id':1, 'project_name':'ipad', 'price':2000, 'count':30}
project_title = mix_dict.values()
print(type(project_title))  # dict_values 该类型是一个伪列表,不具备列表的所有功能
print(project_title[0])  # 报错 TypeError
# 通过list()函数定义封装成列表,则具备列表的所有功能
project_title_01 = list(mix_dict.values())
print(project_title_01)
print(project_title_01[0])
project_title_01.append('top')
print(project_title_01)

# 获取字典key的值; []中括号方法,get()方法
user_info = {
    'id':1,
    'username':'abcd',
    'password':'zxcvb',
    'created_time':'2022-6-6 11:11:11'
}
# []中括号方法  key不存在时,则报KeyError错误
values = []
values.append(user_info['id'])
values.append(user_info['username'])
values.append(user_info['password'])
values.append(user_info['created_time'])
print(values)

# values.append(user_info['birthday'])  # 该key不存在,报错
# print(values)
# get()方法
values.append(user_info.get('birthday','2022-3-3'))  # 也可自定义输入value值
values.append(user_info.get('sex'))  # key不存在时,返回默认值None
print(values)

# 字典的删除 clear(), pop(), del
projects = {
    'ipad':{'name':'ipad','price':2200,'desc':'平板电脑'},
    'iphone':{'name':'iphone','price':3000,'desc':'智能手机'},
    'pc':{'name':'pc','price':5000,'desc':'台式电脑'},
    'mac':{'name':'mac','price':8000,'desc':'平板电脑'}
}
# pop()函数,删除字典中的某个key的值并返回
print(projects.keys())
print( '一个中学生购买了{}, 价格是{}。'.format( projects['pc']['name'],projects['pc']['price'] ) )
projects.pop('pc')
print( '库存还剩下{}'.format(projects.keys()))

result = projects.pop('mac')
print( '一个程序员购买了{},它的价格是{}'.format(result['name'],result['price']) )
print('库存还剩下{}'.format(projects.keys()))

# clear() 清空字典中的数据
print('{} 和 {} 都被卖出了,他们一共花费了 {} 元'.format(
    projects['ipad']['name'],projects['iphone']['name'],
    projects['ipad']['price'] + projects['iphone']['price']
))
projects.clear()
print(projects.keys())
# del 删除字典变量
del projects
print(projects)  # 由于del 删除了字典变量,故输出报错NameError


# 字典的复制 copy()函数
fruits = {
    'apple': 10,
    'banana':50,
    'pear':100
}
print(fruits)
# copy()函数
new_fruits = fruits.copy()
new_fruits['orange'] = 50
new_fruits.update({'cherry':100})
print(new_fruits)

new_fruits['apple'] = new_fruits['apple'] + 10
print(new_fruits)
new_fruits['pear'] -= 10
print(new_fruits)

new_fruits.clear()
print(new_fruits)
print('第二天。。。。')
new_fruits = fruits.copy()
print(new_fruits)

# 字典成员运算符 in和not in ,get()方法;推荐使用in与not in
test_dict = {'a':None,'b':1,'c':0,'d':''}
print('a' in test_dict)  # 返回True
print( bool(test_dict.get('a')) )  # 返回false; 因为get方法是把key的值做判断,a的值为None,故返回一个False
print(bool(test_dict.get('b')))   # 返回True

print('f' in test_dict)
print('f' not in test_dict)

# 字典中的末尾删除函数popitem()
students = {'xiaoming':'', 'xiaoyun':'','xiaobai':'在呢','xiaoxin':'我在','xiaomu':'来了'}

print('xiaomu 在吗')
xiaomu = students.popitem()
print('{} 喊 {}'.format(xiaomu[0], xiaomu[1]))

print('xiaoxin 在吗')
xiaoxin = students.popitem()
print('{} 喊 {}'.format(xiaoxin[0], xiaoxin[1]))

print('xiaobai 在吗')
xiaobai = students.popitem()
print('{} 喊 {}'.format(xiaobai[0], xiaobai[1]))

print('xiaoyun 在吗')
xiaoyun = students.popitem()
print('{} 喊 {}'.format(xiaoyun[0], xiaoyun[1]))

print('xiaoming 在吗')
xiaoming = students.popitem()
print('{} 喊 {}'.format(xiaoming[0], xiaoming[1]))

print(students)

 集合的常用方法(待写)

 

 

 

 

 

 

数据类型与布尔值的关系

 

posted @ 2022-06-25 23:26  奔跑在路上you  阅读(115)  评论(0编辑  收藏  举报