字典
字典dictionary
字典是另外一种可变容器类型,且可以存储任意类型对象。列表元素进行修改的话,通过索引进行修改,如果当前元素的顺序发生改变,此时还需要修改索引才能完成修改。然而字典既能存储多个数据,又能方便准确的定位元素。
创建字典
语法:
字典名 = {key1:value1,key2:value2,...}
示例:
student = {'name':'tom','age':18,'sex':'男'}
访问字典
students = {'name':'张三','age':18,'address':'北京'}
print(students['name']) #根据key找到值
返回结果:
张三
修改字典
通过找到指定的key进行修改
students = {'name':'张三','age':18,'address':'北京'}
students['name'] = '李四'
print(students)
返回结果:
{'name': '李四', 'age': 18, 'address': '北京'}
添加字典元素
students = {'name':'张三','age':18,'address':'北京'}
students['hobby'] = '足球'
print(students)
返回结果:
{'name': '张三', 'age': 18, 'address': '北京', 'hobby': '足球'}
删除字典
del 字典名[key]
:指定key删除
students = {'name':'张三','age':18,'address':'北京'}
del students['address'] #指定key删除元素
print(students)
返回结果:
{'name': '张三', 'age': 18}
del 字典名
:删除字典
students = {'name':'张三','age':18,'address':'北京'}
del students #删除字典,删除后结果为NameError: name 'students' is not defined,未定义
print(students)
返回结果:
NameError: name 'students' is not defined
字典名.clear()
:清空整个字典元素,保留一个空的字典
students = {'name':'张三','age':18,'address':'北京'}
students.clear()
print(students)
返回结果:
{}
字典函数
len(dict)
:计算字典中元素的个数
dict1 = {'name':'tom','age':18,'sex':'男','hobby':'足球'}
print(len(dict1))
返回结果:
4
str(dict)
:输出字典,也可打印的字符串表示
dict1 = {'name':'tom','age':18,'sex':'男','hobby':'足球'}
str1 = str(dict1)
print(str1)
print(type(str1)) #判断str1的数据类型
返回结果:
{'name': 'tom', 'age': 18, 'sex': '男', 'hobby': '足球'}
<class 'str'>
type(variable)
:返回输入变量的数据类型,如果变量是字典就返回<class 'dict'>
dict1 = {'name':'tom','age':18,'sex':'男','hobby':'足球'}
print(type(dict1))
返回结果:
<class 'dict'>
dict.fromkeys(seq[,value])
:创建一个新字典,以序列seq元素做字典的值,value为字典所有键对应的初始值
seq = ('name','age','sex')
dict1 = dict.fromkeys(seq)
print("新字典为:",dict1)
dict2 = dict.fromkeys(seq,'jack')
print("新字典为:",dict2)
返回结果:
新字典为: {'name': None, 'age': None, 'sex': None}
新字典为: {'name': 'jack', 'age': 'jack', 'sex': 'jack'}
dict.get(key,default=None)
:返回指定键的值,如果值不在字典中返回default值,如果字典存在该key对应的元素,就输出原值,否则输出该key输入值
dict1 = {'name':'tom','age':18}
print("age键的值为:",dict1.get('age',9))
print("sex键的值为:",dict1.get('sex','男'))
返回结果:
age键的值为: 18
sex键的值为: 男
key in dict
:如果key在字典dict中则返回True,否则返回False
dict1 = {'name':['tom','jack'],'age':19,'sex':'男','hobby':'足球'}
if 'name' in dict1:
print("键name在字典中存在")
else:
print("键name在字典中不存在")
返回结果:
键name在字典中存在
dict.keys()
:以列表返回一个字典所有键名
dict1 = {'name':['tom','jack'],'age':19,'sex':'男','hobby':'足球'}
print(dict1.keys())
返回结果:
dict_keys(['name', 'age', 'sex', 'hobby'])
dict.setdefault(key,default=None)
:和get类似,但如果键不存在字典中,将会添加键并将值设为default
dict1 = {'name':'tom','age':19}
print("age键的值为:",dict1.setdefault('age',9))
print("sex键的值为:",dict1.setdefault('sex','男'))
print("新字典为:",dict1)
返回结果:
age键的值为: 19
sex键的值为: 男
新字典为: {'name': 'tom', 'age': 19, 'sex': '男'}
dict.values()
:以列表返回一个字典中的所有值
dict1 = {'name':'tom','age':19}
print(dict1.values())
print(dict1.items()) #将键值对返回并且返回至元组中
返回结果:
dict_values(['tom', 19])
dict_items([('name', 'tom'), ('age', 19)])
元组
元组tuple
元组和列表类似,不通过之处在于元组的元素不能被修改,而列表元素是可以被修改的,也可以进行分片和连接操作。元组使用小括号()创建,列表使用中括号[]创建。
元组的创建语法
元组名 = (元素1,元素2,元素3,...)
示例
student = ('jack','tom','jone')
删除元组
语法:del 元组名
示例:
tuple1 = ('abc',123,'hello')
print("删除之前的元组为:",tuple1)
del tuple1
print("删除后的元组为:",puple1) #因为del删除是在内存中彻底将元组删除,即删除后结果为名称未定义,找不到元组名
返回结果:
删除之前的元组为: ('abc', 123, 'hello')
print("删除后的元组为:",puple1)
NameError: name 'puple1' is not defined
元组切片截取
元组的元素虽然不能够被改变,但是元组也是一个序列,也可以通过索引去访问和截取元组中指定位置的元素
tup01 = ('tom','jack','aimi','lili','black')
print(tup01[0:3])
返回结果:
('tom', 'jack', 'aimi')
多维元组
多维元组就是在元祖中包含元组,元祖中的元素可以是一个新的元组
tup01 = ('tom','jack',['aimi','lili'],'black')
print(tup01[2][1])
返回结果:
lili
元组函数
len(tuple)
:计算元组中素的个数
tup01 = ('tom','jack','aimi','lili','black')
print(len(tup01)) #统计元组中元素的个数
返回结果:
5
max(tuple)
:返回元组中元素的最大值
tup01 = (2,6,5,8,9)
print(max(tup01))
返回结果:
9
min(tuple)
:返回元祖中元素的最小值
tup01 = (2,6,5,8,9)
print(min(tup01))
返回结果:
2
tuple(list)
:将列表转换为元组
students = ['jack','tom','john','amy','kim','sunny']
print('转换前:',students)
print('转换后:',tuple(students))
print('再次转换后:',list(students))
返回结果:
转换前: ['jack', 'tom', 'john', 'amy', 'kim', 'sunny']
转换后: ('jack', 'tom', 'john', 'amy', 'kim', 'sunny')
再次转换后: ['jack', 'tom', 'john', 'amy', 'kim', 'sunny']
列表
列表list
列表是由一系列按特定顺序排列的元素组成,列表能存储多种数据类型,其中的元素之间可以没有任何关系。
访问列表元素
list01 = ['jack','jane','black']
print(list01[2]) #通过下标获取black
返回结果:
black
修改列表元素
修改列表元素的语法和访问列表元素的语法类似,指定列表名和要修改的索引,在指定新值
list01 = ['jack','jane',['dahei','joe'],'black']
list01[0] = 'lili' #通过下标获取列表元素,并赋予新值
print(list01)
list01[2][0] = 'susan' #通过下标获取列表元素,并赋予新值
print(list01)
#列表是一个可变的类型数据,允许我们对立面的元素进行修改
返回结果:
['lili', 'jane', ['dahei', 'joe'], 'black']
['lili', 'jane', ['susan', 'joe'], 'black']
添加元素
append
:列表末尾添加元素
list02 = ['jack','jane',['dahei','joe'],'black']
list02.append('susan') #在列表末尾添加元素susan
print(list02)
返回结果:
['jack', 'jane', ['dahei', 'joe'], 'black', 'susan']
insert
:列表指定下标位置添加元素
list02 = ['jack','jane',['dahei','joe'],'black']
print(list02) #修改前
print('_'*40)
list02.insert(3,'susan')
print(list02) #修改后
返回结果:
['jack', 'jane', ['dahei', 'joe'], 'black']
________________________________________
['jack', 'jane', ['dahei', 'joe'], 'susan', 'black']
删除元素
pop()
:默认删除最后一个,可以指定位置删除,并且删除时返回删除内容
list03 = ['jack','jane','joe','black']
print('删除前的元素为:',list03)
print('_'*40)
print('默认删除的元素为:',list03.pop()) #默认删除操作,并且返回删除的元素
print('删除后的剩余元素为:',list03)
print('_'*40)
print('继续删除的元素为:',list03.pop(1)) #指定删除操作,并且返回删除的元素
print('删除后的剩余元素为:',list03)
返回结果:
删除前的元素为: ['jack', 'jane', 'joe', 'black']
________________________________________
默认删除的元素为: black
删除后的剩余元素为: ['jack', 'jane', 'joe']
________________________________________
继续删除的元素为: jane
删除后的剩余元素为: ['jack', 'joe']
del
:指定位置删除,不加位置删除的话,删除元素包括列表名称
list03 = ['jack','jane','joe','black']
print('删除前的元素为:',list03)
print("_"*40)
#del list03 #从内存中彻底删除,包括列表名
del list03[1]
print('删除后剩余的元素为:',list03)
返回结果:
删除前的元素为: ['jack', 'jane', 'joe', 'black']
________________________________________
删除后剩余的元素为: ['jack', 'joe', 'black']
remove()
:当不知道元素索引,只知道元素值的时候,使用
remove()方法删除元素
list03 = ['jack','jane','joe','black']
print('删除前的元素为:',list03)
print("_"*40)
list03.remove('joe') #通过元素值进行删除
print('删除后剩余元素:',list03)
返回结果:
删除前的元素为: ['jack', 'jane', 'joe', 'black']
________________________________________
删除后剩余元素: ['jack', 'jane', 'black']
list.clear()
:用于清空列表,返回空列表
list06 = ['jack','jane','joe','black']
list06.clear()
print(list06)
返回结果:
[]
查找元素
in(存在)
,如果存在那么结果为True,否则为False
list04 = ['jack','jane','joe','black']
name1 = 'jane'
print(name1 in list04) #in存在返回True
name2 = 'blacks'
print(name2 in list04) #in不存在返回False
返回结果:
True
False
not in(不存在)
,如果存在那么结果为False,不存在返回True
list04 = ['jack','jane','joe','black']
name1 = 'jane'
print(name1 not in list04) #not in存在返回False
name2 = 'blacks'
print(name2 not in list04) #not in不存在返回True
返回结果:
False
True
列表函数
len(list)
:查看列表的长度(个数)
list05 = ['jack','jane','joe','black']
print(len(list05)) #返回列表的长度(个数)4
返回结果:
4
max(list)
:返回列表元素中的最大值。默认数值类型的参数,取最大值。字符型的参数,取字母排序靠后者
list05 = ['jack','jane','joe','black','z']
print(max(list05)) #字符返回列表中字符串尾部排序靠后
age = [1,2,22,33]
print(max(age)) #数字返回列表中最大值
返回结果:
z
33
min(list)
:返回列表元素中的最小值。默认数值类型的参数,取最小值。字符型的参数,取字母排序靠前者。
list05 = ['jack','jane','joe','black','a']
print(min(list05)) #字符返回列表中字符串头部排序靠后
age = [1,2,22,33]
print(min(age)) #数字返回列表中最小值
返回结果:
a
1
list.count(obj)
:统计某个元素在列表中出现的次数
list05 = ['jack','jane','joe','black','joe','a']
print(list05.count('joe'))
返回结果:
2
extends(list)
:扩展列表,在一个列表的末尾一次性追加一个新的列表,参数为一个列表
list05 = ['jack','jane','joe','black']
list06 = ['kim','amy']
list05.extend(list06)
print(list05)
返回结果:
['jack', 'jane', 'joe', 'black', 'kim', 'amy']
list.index(obj)
:用于从列表中找出某一个值第一个匹配项的索引位置
list05 = ['jack','jane','joe','black']
print(list05.index('joe'))
返回结果:
2
list.reverse()
:反向列表中的元素,倒序
list05 = ['jack','jane','joe','black']
list05.reverse()
print(list05)
返回结果:
['black', 'joe', 'jane', 'jack']
list.sort()
:对列表进行排序,该方法没有返回值。更改的是原数组
list06 = [4,2,8,9,10]
list06.sort()
print(list06)
返回结果:
[2, 4, 8, 9, 10]
list.copy()
:复制列表
list06 = ['jack','jane','joe','black']
print("复制前:",list06)
print('-'*40)
print("复制后:",list06.copy())
返回结果:
复制前: ['jack', 'jane', 'joe', 'black']
----------------------------------------
复制后: ['jack', 'jane', 'joe', 'black']
字符串常用函数
Python字符串(string)常用函数
find
:检测字符串是否包含指定字符,如果存在则返回开始的索引值,否则返回-1
str1 = 'hello world'
print(str1.find('w')) #存在,则返回是该字符串位置
print(str1.find('z')) #不存在,则返回-1
返回结果:
6
-1
index
:检测字符串是否包含指定字符,若果存在返回开始的索引值,否则提示错误信息
str1 = 'hello world'
print(str1.index('d')) #存在,则返回该字符串位置
print(str1.index('z')) #不存在,提示错误信息
返回结果:
10
print(str1.index('z')) #不存在,提示错误信息
ValueError: substring not found
count
:返回字符串指定索引范围内[start,end]出现的次数
str1 = 'hello world'
print(str1.count('o')) #统计该字符串出现的次数
print(str1.count('l',2,10)) #指定位置查找,指定第2到第10位字符串之间
返回结果:
2
3
replace
:替换,将str1替换成str2,如果指定count,则不超过count次
str1 = 'hello world hello python'
print(str1.replace('hello','go out')) #将hello替换为go out
返回结果:
go out world go out python
split
:切割,指定值进行切割
str1 = 'hello world hello python hello china hello hello hello hello'
print(str1.split('o')) #指定字符进行切割,默认输出到列表中
print(str1.split('o',3)) #指定字符串进行切割,从指定位置之后的不进行切割
返回结果:
['hell', ' w', 'rld hell', ' pyth', 'n hell', ' china hell', ' hell', ' hell', ' hell', '']
['hell', ' w', 'rld hell', ' python hello china hello hello hello hello']
capitalize
:将字符串的首字母大写
str1 = 'hello world hello python'
print(str1.capitalize())
返回结果:
Hello world hello python
title
:将字符串中每个单词的首字母进行大写
str1 = 'hello world'
print(str1.title()) #将每个单词的首字母大写
返回结果:
Hello World
startswith
:检查字符串是否是指定字符开头,是则返回True,否则返回False
str1 = 'hello world hello china'
print(str1.startswith('hello')) #是,则返回True
print(str1.startswith('world')) #否,则返回False
返回结果:
True
False
endswith
:检查字符串是否是指定字符结尾,是则返回True,否则返回False
str1 = 'hello world hello china'
print(str1.endswith('china')) #是,则返回Ture
print(str1.endswith('hello')) #否,则返回False
返回结果:
True
False
lower
:将字符串转换为小写
str1 = 'Hello World HELLO CHINA'
print(str1.lower()) #将字符串转换为小写
返回结果:
hello world hello china
upper
:将字符串转换为大写
str1 = 'hello world hello china'
print(str1.upper()) #将字符串转换为大写
返回结果:
HELLO WORLD HELLO CHINA
ljust
:返回一个字符串左对齐,并使用空格填充至长度width的新字符串
str1 = 'hello'
print(str1.ljust(10)) #左对齐,字符右侧由空格填充至指定长度
返回结果:
hello #选中查看效果
rjust
:返回一个字符串右对齐,并使用空格填充至长度width的新字符串
str1 = 'hello'
print(str1.rjust(10)) #右对齐,字符左侧由空格填充至指定长度
返回结果:
hello #选中查看效果
center
:返回一个源字符串居中,并使用空格填充至长度width的新字符串
str1 = 'hello'
print(str1.center(15)) #居中对齐,字符左右两侧由空格填充至指定长度
返回结果:
hello #选中查看效果
lstrip
:去除字符串左边空白字符
str1 = ' hello'
print(str1) #默认输出字符串结果左边携带空格字符
print(str1.lstrip()) #去除字符串左边空格后结果
返回结果:
hello
hello
rstrip
:去除字符串右边空白字符
str1 = 'hello '
print(str1) #默认输出字符串结果右边携带空格字符
print(str1.rstrip()) #去除字符串右边空格后结果
返回结果:
hello #默认情况
hello
strip
:去除字符串两遍空白字符
str1 = ' hello '
print(str1) #默认输出字符串结果左右两遍携带空格字符
print(str1.strip()) #去除后字符串左右两遍空格后结果
返回结果:
hello #默认情况
hello
partition
:可以根据指定将字符串进行分割,成为三个部分
str1 = 'hello world hello china'
print(str1.partition('world')) #指定字符串进行分割为三部分
返回结果:
('hello ', 'world', ' hello china')
join
:在str2中每个两个字符中间面插入str1中内容,构造出一个新的字符串
str1 = '_'
str2 = ['hello','world','hello'] #在每两个字符中间插入一个str1中内容,使之组成新的字符
print(str1.join(str2))
返回结果:
hello_world_hello
isspace
:如果str1中只包含空格,则返回True,否则返回False
str1 = ' '
str2 = ' hello'
print(str1.isspace())
print(str2.isspace())
返回结果:
True
False
isdigit
:如果str1只包含数字则返回True,否则返回False
str1 = 'a123'
str2 = '123'
print(str1.isdigit()) #返回False,包含字母
print(str2.isdigit()) #返回True,只包含数字
返回结果:
False
True
isalnum
:如果str1所有字符都是字母或数字则返回True,否则返回False
str1 = 'a123'
print(str1.isalnum()) #返回True,只包含数字
返回结果:
True
isalpha
:如果str1所有字符都是都是字母,则返回True,否则返回False
str1 = 'abc'
print(str1.isalpha()) #返回True,只包含字母
返回结果:
True
-
1 2