您的位置:首页 > 编程语言 > Python开发

Python基础 -- 02 基础语法(字符串、列表、元组、字典、set集合)

2018-01-10 11:39 1061 查看

一、字符串

1、字符串定义格式

双引号或者单引号中的数据,就是字符串
b = "hello itcast.cn"
或者
b = 'hello itcast.cn'

2、字符串的输出

name = "张飞"
print("姓名:%s,字翼德"%name)
"""
输出结果:
姓名:张飞,字翼德
"""

3、字符串的输入

name = input("请输入名字:")
print("姓名:%s,字翼德"%name)
"""
输出结果:
请输入名字:张飞
姓名:张飞,字翼德
"""注意:input获取的数据,都以字符串的方式进行保存,即使输入的是数字,那么也是以字符串方式保存

4、下标和切片

(1)、下标
        列表与元组支持下标索引好理解,字符串实际上就是字符的数组,所以也支持下标索引。



索引使用演示:
s = "abcdefg"
i = 0
while i < 7:
ch = s[i]
print("索引为%d处的元素是:%s" %(i,ch))
i += 1
"""
输出结果:
索引为0处的元素是:a
索引为1处的元素是:b
索引为2处的元素是:c
索引为3处的元素是:d
索引为4处的元素是:e
索引为5处的元素是:f
索引为6处的元素是:g
"""(2)、切片
        切片是指对操作的对象截取其中一部分的操作。字符串、列表、元组都支持切片操作。
切片语法:字符串[起始:结束:步长]
s[::]代码演示:"""
切片代码演示:
"""
s = "hello world"
print(s[:]) # hello world 截取全部字符串
print(s[1:]) # ello world 从索引为1处开始截取字符串
print(s[:1]) # h 从开始截取到索引为1的字符串(不包括索引为1的字符)
print(s[2::2]) # lowrd 从索引为2处开始截取字符串,每次增加两个索引
print(s[1:-2]) # ello wor 索引为负数是从后向前数。从索引为1处开始截取字符串,一直到索引为-2的地方结束,不包括索引为-2
print(s[-7:-2]) # o wor
"""
python面试题:最快的反转字符串的方法
"""
print(s[::-1]) # dlrow olleh 步长为-1时,是从后向前数每次数1个注意:当[]中没有:号时,是取索引字符,当[]中有:时,则是截取字符串

5、字符串中常见的操作

(1)、index:遍历mystr,查找子串是否在mystr中,如果有,返回找到的第一个子串的元素索引值,没有则标错
语法介绍:
#str:子串
#start:开始索引
#end:结束索引
mystr.index(str,start,end)代码演示:
mystr = "hello world!!! This is my third python lesson , and I love python!!!"

"""
#str:子串
#start:开始索引
#end:结束索引
#mystr.index(str,start,end)
"""

print(mystr.index("python")) # 32
print(mystr.index("python",20)) # 32
print(mystr.index("python",33)) # 59
print(mystr.index("python",60)) # 从60索引开始查找,没有找到python的字符串,直接报错
print(mystr.index("python",33,50)) # 在33索引和50索引直接查找,没有找到python的字符串,直接报错(2)、find:检测 str 是否包含在 mystr中,如果是返回开始的索引值,否则返回-1,如果有多个str,则只返回第一个的索引值

语法介绍:
mystr.find(str, start=0, end=len(mystr))
代码演示:
mystr = "hello world!!! This is my third python lesson , and I love python!!!"

"""
#str:子串
#start:开始索引
#end:结束索引
#mystr.find(str,start,end)
"""

print(mystr.find("python"))        # 32
print(mystr.find("python",20))     # 32
print(mystr.find("python",33))     # 59
print(mystr.find("python",60))     # 从60索引开始查找,没有找到python的字符串,直接返回-1
print(mystr.find("python",33,50))  # 在33索引和50索引直接查找,没有找到python的字符串,直接返回-1
(3)、count:返回 str在start和end之间 在 mystr里面出现的次数,如果没有,返回0
语法介绍:
mystr.count(str, start=0, end=len(mystr))代码演示:
mystr = "hello world!!! This is my third python lesson , and I love python!!!"

"""
#str:子串
#start:开始索引
#end:结束索引
#mystr.count(str,start,end)
"""

print(mystr.count("python")) # 2
print(mystr.count("python",20)) # 2
print(mystr.count("python",33)) # 1
print(mystr.count("python",60)) # 从60索引开始查找,没有找到python的字符串,直接返回0
print(mystr.count("python",33,50)) # 在33索引和50索引直接查找,没有找到python的字符串,直接返回0(4)、isdigit:判断用户输入的字符串是否是整型的数字,如果是,返回True,否则,返回False语法介绍:
mystr.isdigit()代码演示:
input = input("请输入整型数字字符串:")

if input.isdigit():
print("输入正确")
else:
print("请输入正确类型的字符串。")(5)、isalpha:判断字符串是否由纯字符组成,如果是,返回True,否则,返回False语法介绍:
mystr.isalpha()代码演示:
str = input("请输入纯母组成的字符串:")

while not str.isalpha():
str = input("请输入纯母组成的字符串:")(6)、isspace:判断字符串是否是全部都由空格组成,如果是,返回True,否则返回False(7)、startswith:判断字符串是否是以指定字符开始,如果是,返回True,否则返回False
语法介绍:
mystr.startswith(str,startIndex,endIndex)代码演示:
str = "hello world!!!"

print(str.startswith("h")) # True
print(str.startswith("hell")) # True
print(str.startswith("o",2)) # False
print(str.startswith("l",2)) # True
print(str.startswith("e",1,5)) # True(8)、endswith:判断字符串是否以指定子串结尾,如果是,返回True,否则,返回False代码演示:
str = "hello world!!!"

print(str.endswith("l")) # False
print(str.endswith("d!!!")) # True
print(str.endswith("
4000
!!",2)) # False
print(str.endswith("o",1,5)) # True(9)、replace:替换字符串中的指定子串为另一个子串
语法介绍:
oldStr:被替换掉的源字符串
newStr:替换为的新字符串
count:要替换的个数,默认是全都替换
str.replace(oldStr,newStr,count)代码演示:
str = " hello world!!! This is my first Python lesson, I very like Python"

"""
oldStr:被替换掉的源字符串
newStr:替换为的新字符串
count:要替换的个数,默认是全都替换
str.replace(oldStr,newStr,count)
"""

print(str.replace("Python","java")) # hello world!!! This is my first java lesson, I very like java
print(str.replace("Python","java",0)) # hello world!!! This is my first Python lesson, I very like Python
print(str.replace("Python","java",1)) # hello world!!! This is my first java lesson, I very like Python(10)、strip:去除首尾的空格语法介绍:
str.strip()
衍生函数:
lstrip:去掉左边的空格
rstrip:去掉右边的空格
(11)、split:按照指定字符分割字符串,返回列表
语法介绍:
str.split()代码演示:
str = " hello world!!! This is my first Python lesson, I very like Python "

arr = str.split(" ")
print(arr)
# ['', 'hello', 'world!!!', 'This', 'is', 'my', 'first', 'Python', 'lesson,', 'I', 'very', 'like', 'Python', '', '']

arr = str.split("s")
print(arr)
# [' hello world!!! Thi', ' i', ' my fir', 't Python le', '', 'on, I very like Python '](12)、lower:将字符串中所有大写字母转换成小写字母(13)、upper:将字符串中所有的小写字母转换成大写字母
(14)、swapcase:将字符串中的大小写字母互转,即大写转小写,小写转大写
(15)、capitalize:将字符串中的首字母大写,其余字母全部小写
(16)、title:将字符串中所有单词的首字母大写,其余字母都小写
(17)、partition:将字符串按照指定的子串分割成三部分,返回列表,子串是其中第二部分
语法介绍:
mystr.partition(str)代码演示:
str = " hello world!!! This is my first Python lesson, I very like Python "

arr = str.partition("first")
print(arr) # (' hello world!!! This is my ', 'first', ' Python lesson, I very like Python ')
print(arr[0]) # hello world!!! This is my(18)、center:给定一个长度,将字符串居中对齐(长度要大于字符串长度)(19)、len:查看字符串所占的元素的个数
语法介绍:
len(str)代码演示:
str = " hello "

print(len(str))

6、字符串操作的课后练习

(1)、字符串切片的处理
str = "1234567890"

# 截取字符串的第一位到第三位之间的元素
print(str[0:3])

# 截取字符串最后三位的字符
print(str[-3:])

# 截取字符串的全部字符
print(str[:])

# 截取字符串的第7个字符到结尾
print(str[6:])

# 截取字符串的第1位到倒数第3位(不包括倒数第3位)之间的字符
print(str[0:-3])

# 截取字符串的倒数第一个字符
print(str[-1:])

# 截取与源字符串相反的字符串
print(str[::-1])

# 截取字符串倒数第3位与倒数第1位之间的字符
print(str[-3:-1])

# 截取字符串的第1位到最后一位字符之间的字符,每隔一个字符截取一次
print(str[0:-1:2])
print(str[:-1:2])

二、列表

1、列表的格式:

list = [元素,元素,元素]注意:同一个列表中可以放置不同的数据类型的元素,但是建议没个列表只放置一种元素。

2、列表的循环遍历

(1)、使用for循环遍历
nameList = ["zhangsan","list","wangwu"]

for name in nameList:
print(name,end="\t") # zhangsan list wangwu(2)、使用while循环遍历
nameList = ["zhangsan","list","wangwu"]

# 求出列表长度
length = len(nameList)

i = 0

while i < length:
print(nameList[i],end="\t") # zhangsan list wangwu
i += 1

3、列表的创建

# 方式 1 :直接创建列表
nameList = ["zhangsan","lisi","wangwu"]

"""
方式 2 :同过使用内置的range()函数生成等差数列,放入列表中
语法:range(startNum, endNum, step)
startNum:等差数列开始的数字,
endNum:等差数列结束的数字,等差数列中不包含该数字
step:等差数列中每个元素的差值,默认是1
或:
range(num)
num:等差数列的个数,默认是0开始,步长是1
"""
print(list(range(5))) # [0, 1, 2, 3, 4]
print(list(range(5,10,2))) # [5, 7, 9]

4、增加列表数据

insert、append、extend
nameList = ["zhangsan","lisi","wangwu"]

"""
insert(index,str) : 向列表指定的下表插入一个数据,原数据和元数据之后的元素默认向后移动一个位置

"""
nameList.insert(2,"zhaoliu")
print(nameList) # ['zhangsan', 'lisi', 'zhaoliu', 'wangwu']

"""
append() : 在列表末尾追加数据
"""
nameList.append("sunqi")
nameList.append(100)
nameList.append([1,2,3])
print(nameList) # ['zhangsan', 'lisi', 'zhaoliu', 'wangwu', 'sunqi', 100, [1, 2, 3]]

"""
extend() : 在列表末尾追加一个数据,不能追加数字类型的数据,
如果要追加的是一个字符串,则将字符串的每个字符单独追加到列表中,
如果要追加的数据是列表,则将列表的每个元素单独追加到源列表的末尾
"""
nameList.extend("aaa") # ['zhangsan', 'lisi', 'zhaoliu', 'wangwu', 'sunqi', 100, [1, 2, 3], 'a', 'a', 'a']
print(nameList)
nameList.extend(["aaa",12.4,4]) # ['zhangsan', 'lisi', 'zhaoliu', 'wangwu', 'sunqi', 100, [1, 2, 3], 'a', 'a', 'a', 'aaa', 12.4, 4]
print(nameList)

5、查询列表数据

list = ['zhangsan', 'lisi', 'zhaoliu', 'wangwu', 'sunqi', 100, [1, 2, 3], 'a', 'a', 'a', 'aaa', 12.4, 4]

"""
in / not in : 判断数据是否存在
"""
if "zhangsan" in list :
print("张三在")
else:
print("张三不在")

"""
list.index(str) : 判断元素str是否在list中,如果存在,返回索引,如果不存在,报错
"""
print(list.index("zhangsan")) # 0
print(list.index("aaaa")) # 报错

"""
list.count(str) : 返回指定元素在列表中的个数,如果没有,返回0
"""
print(list.count("aaaaa")) # 0
print(list.count("lisi")) # 1

6、修改列表数据

list = ['zhangsan', 'lisi', 'zhaoliu', 'wangwu', 'sunqi', 100, [1, 2, 3], 'a', 'a', 'a', 'aaa', 12.4, 4]

"""
列表数据的修改
"""
if "zhangsan" in list:
list[list.index("zhangsan")] = "zhangsan1"
else:
print("张三不在")
print(list) # ['zhangsan1', 'lisi', 'zhaoliu', 'wangwu', 'sunqi', 100, [1, 2, 3], 'a', 'a', 'a', 'aaa', 12.4, 4]

7、删除列表数据

list = ['zhangsan', 'lisi', 'zhaoliu', 'wangwu', 'sunqi', 100, [1, 2, 3], 'a', 'a', 'a', 'aaa', 12.4, 4]

"""
列表数据的删除
"""
# remove(str) : 删除列表中指定的元素,如果元素不存在,则报错
list.remove([1,2,3])
print(list) # ['zhangsan', 'lisi', 'zhaoliu', 'wangwu', 'sunqi', 100, 'a', 'a', 'a', 'aaa', 12.4, 4]

# pop() : 删除列表内指定的下标的数据,并返回该数据,如果没有指定参数,则默认操作最后一条数据
print(list.pop(2)) # zhaoliu
print(list) # ['zhangsan', 'lisi', 'wangwu', 'sunqi', 100, 'a', 'a', 'a', 'aaa', 12.4, 4]
print(list.pop()) # 4
print(list) # ['zhangsan', 'lisi', 'wangwu', 'sunqi', 100, 'a', 'a', 'a', 'aaa', 12.4]

# clear() : 清空列表数据,但是不删除列表
list.clear()
print(list) # []

8、列表的排序和逆置

"""
列表的排序
"""
# sort() : 列表提供的排序方法,默认从小到大的方式排序,如果想要从大到小排序,加上参数:reverse= True
# sort() 该方法是在元列表基础上进行修改
# python2 中支持混合数据类型的列表的排序
# python3 中不支持混合数据类型的列表的排序

numList = [1,2.3,75,12.6,-5,99]
numList.sort();
print(numList) # [-5, 1, 2.3, 12.6, 75, 99]
numList.sort(reverse=True)
print(numList) # [99, 75, 12.6, 2.3, 1, -5]

# sorted() : python内置函数,Python提供的排序方法,该方法创建一个新的列表,元列表不变
# 如果想要从大到小排序,加上参数:reverse= True
nameList = ["sdf","egsd","ge","ggfa"]
print(nameList) # ['sdf', 'egsd', 'ge', 'ggfa']
print(sorted(nameList)) # ['egsd', 'ge', 'ggfa', 'sdf']
print(nameList) # ['sdf', 'egsd', 'ge', 'ggfa']

"""
reverse() : 将列表倒置
"""
list = [1,2,3,4,5,6,7]
list.reverse()
print(list) # [7, 6, 5, 4, 3, 2, 1]

9、列表的浅拷贝和深拷贝

numList = [10,20,30,40]
"""
浅拷贝:只是增加了一个数据的引用,修改任何一个引用数据,都会导致源数据的修改
"""
numList1 = numList
print(numList1) # [10, 20, 30, 40]
print(id(numList1)) # 3176773767944
print(id(numList1)) # 3176773767944
numList1[2] = 50
print(numList) # [10, 20, 50, 40]

"""
深拷贝:copy() 拷贝一份数据赋值给一个新的列表,和元列表没有关系
"""
newList = numList.copy()
print(id(newList)) # 1995765240712
print(id(numList)) # 1995765240584

10、列表推导式(列表生成式) ♚♚♚

"""
列表的推导式
"""
# 创建一个1 ~ 21 之间的所有偶数的列表
# 使用range() 加 for循环的写法
numList = []
for i in range(1,21):
if i % 2 == 0:
numList.append(i)
print(numList) # [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]

# 使用列表推导式
numList1 = [i for i in range(1,21) if i % 2 == 0]
print(numList1) # [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
# 该列表推导式跟使用range和for循环生成的方式一样

###########################################################################

"""
创建一个1 ~ 21 之间的所有偶数平方的列表
"""
# 使用range()加for循环的写法
numList2 = []
for i in range(1,21):
if i % 2 == 0:
numList2.append(i ** 2)
print(numList2) # [4, 16, 36, 64, 100, 144, 196, 256, 324, 400]

# 使用列表推导式生成列表
numList3 = [i ** 2 for i in range(1,21) if i % 2 ==0]
print(numList3) # [4, 16, 36, 64, 100, 144, 196, 256, 324, 400]

11、列表的常用技巧

"""
(⭐⭐⭐⭐⭐)列表的合并
"""
list1 = [10,20,30]
list2 = ["zhangsan","lisi","wangwu"]

list3 = list1 + list2 # list2 的数据追加在 list1 之后,并且生成了一个新的列表
print(id(list1)) # 1954458882824
print(id(list2)) # 1954458882184
print(id(list3)) # 1954458882952
print(list3) # [10, 20, 30, 'zhangsan', 'lisi', 'wangwu']

# 不生成新的列表的合并方法,该方法等同于 extend(): list1.extend(list2)
list1 += list2 # list2 的数据追加在 list1 之后,但是不会生成新的列表,数据都在list1中
print(id(list1)) # 2106811273992
print(id(list2)) # 2106811273352
print(list1) # [10, 20, 30, 'zhangsan', 'lisi', 'wangwu']

"""
(⭐⭐⭐⭐⭐)列表转换为字符串:列表中的所有元素都是字符串类型
"""
# 将字符串转换为列表
str1 = "hello world!!!"
strList = str1.split(" ") # 按照分隔符进行分割
print(strList) # ['hello', 'world!!!']
strList2 = list(str1) # 将字符串的每个字符都当成一个元素,放入列表中
print(strList2) # ['h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd', '!', '!', '!']

# 将列表转换为字符串
print(strList) # ['hello', 'world!!!']
listStr = " ".join(strList) # " ":代表分隔符,即将列表的每个元素按照指定的分隔符进行拼装为字符串
print(listStr) # hello world!!!
listStr2 = "$".join(strList)
print(listStr2) # hello$world!!!

"""
列表转换为字符串:列表中的元素是其他类型
"""
numList = [1,2.1,3.5,12.01,45]
numStr = "".join([str(i) for i in numList])
print(numStr) # 12.13.512.0145

"""
以上写法可以解析为:
for i in numList : 取出 numList 内每个元素
str(i) : 将列表内每个元素转为字符串
[str(i) for i in numList] : 将数组变成字符串数组
"".join([str(i) for i in numList]) : 使用分隔符,将数组转换成字符串
"""

"""
类型判断:
isinstance(str,type) : 判断对象(str)是否是指定的数据类型(type),如果是,返回True,不是则返回False
"""
password = input("请输入密码:")
if isinstance(password, str):
print("输入的密码是字符串类型。")
elif isinstance(password, int):
print("输入的密码是整型。")
else:
print("判断不出来输入的密码是什么类型。")

arrList = [12,34,["11","22"],1.2]
for n in arrList:
if isinstance(n,list):
for m in n:
print(m,end="\t")
else:
print(n, end="\t")
# 打印结果:12 34 11 22 1.2

"""
enumerate() : 返回一个列表,这个列表是包含了源列表的 元素索引 和 元素的值 的元组
"""
nList = [10,20,30,40]
for i in enumerate(nList):
print(i, end="\t") # (0, 10) (1, 20) (2, 30) (3, 40)

for index, value in enumerate(nList):
if index % 2 == 0:
print(index, value) # 0 10 2 30

12、列表操作的课后练习题

(1)、实现求一个元素都为数字的列表的最值
"""
编程实现对一个元素都是数字的列表,求最大值、最小值
"""
numList = [10,25,-5,78,81,12,-52,242,-521]

# 定义最大值最小值
minNum = numList[0]
maxNum = numList[0]

# 遍历列表,求最大值最小值
for num in numList:
if minNum > num:
minNum = num

if maxNum < num:
maxNum = num

print("列表中的最大值是:%d" %maxNum)
print("列表中的最小值是:%d" %minNum)(2)、统计字符串中字符个数
"""
统计字符串中各个字
115bc
符出现的次数
"""
myStr = "kajodgigksggalskghasigewklgastyaskhldgusgy"

# 1.用字符串的 count() 方法进行统计
chList = []

for ch in myStr:
if ch not in chList:
print("字符%s在字符串中出现的次数为:%d" %(ch,myStr.count(ch)))
chList.append(ch)
"""
打印结果:
字符k在字符串中出现的次数为:5
字符a在字符串中出现的次数为:5
字符j在字符串中出现的次数为:1
字符o在字符串中出现的次数为:1
字符d在字符串中出现的次数为:2
字符g在字符串中出现的次数为:9
字符i在字符串中出现的次数为:2
字符s在字符串中出现的次数为:6
字符l在字符串中出现的次数为:3
字符h在字符串中出现的次数为:2
字符e在字符串中出现的次数为:1
字符w在字符串中出现的次数为:1
字符t在字符串中出现的次数为:1
字符y在字符串中出现的次数为:2
字符u在字符串中出现的次数为:1
"""

##################################################################

# 2.用列表的方法进行处理

# ord(ch) : 该方法是将字符转成对应的ASCII码值
# chr(num) : 将数字转换成对应的字符
countList = [0] * 127 # 创建一个由127个0组成的列表
myStr1 = "kajodgigksggalskghasigewklgastyaskhldgusgy"

for s in myStr1:
countList[ord(s)] += 1
# 打印统计之后的列表,列表中对应索引上的值表示的是该索引对应的字符出现的格式
print(countList)
# 使用 enumerate 函数将列表中的index和对应的值取出
for index,num in enumerate(countList):
if num != 0:
print("字符%s出现的次数是:%d" %(chr(index), num))
"""
打印结果:
字符a出现的次数是:5
字符d出现的次数是:2
字符e出现的次数是:1
字符g出现的次数是:9
字符h出现的次数是:2
字符i出现的次数是:2
字符j出现的次数是:1
字符k出现的次数是:5
字符l出现的次数是:3
字符o出现的次数是:1
字符s出现的次数是:6
字符t出现的次数是:1
字符u出现的次数是:1
字符w出现的次数是:1
字符y出现的次数是:2
"""(3)、完成名片管理器
"""
需要完成的基本功能:
添加名片
删除名片
修改名片
查询名片
退出系统
程序运行后,除非选择退出系统,否则重复执行功能
"""

# 定义存放所有用户的列表
userList = []
# 定义管理员密码
password = "admin123"
while True:
print("-----------------------------------")
print("--------- 1.添加名片 --------------")
print("--------- 2.删除名片 --------------")
print("--------- 3.修改名片 --------------")
print("--------- 4.查询名片 --------------")
print("--------- 5.显示全部名片 ----------")
print("--------- 6.退出系统 --------------")
print("----------请输入操作对应序号:------")

# 获取输入的数字
command = int(input())

# 进行操作判断
if command == 1:
# 添加名片
name = input("请输入姓名:")
age = input("请输入年龄:")
gender = input("请输入性别:")
# 将输入的数据添加到用户列表
userList.append([name, age, gender])
print("[INFO]:添加成功")
elif command == 2:
# 删除名片
delName = input("请输入需要删除的人员姓名:")
# 遍历用户列表
for user in userList:
# 判断要删除的人员是否在用户列表中
if delName in user:
# 调用remove方法删除用户
userList.remove(user)
print("[INFO]:删除成功")
break
else:
print("[INFO]:查无此人")
elif command == 3:
# 修改名片
editName = input("请输入需要修改的人员的姓名:")
# 遍历用户列表
for user in userList:
if editName in user:
newName = input("请输入新的姓名:")
newAge = input("请输入新的年龄:")
newGender = input("请输入新的性别:")
# 根据元素查出索引,然后根据索引进行修改列表
userList[userList.index(user)] = [newName, newAge, newGender]
print("[INFO]:修改成功")
else:
print("[INFO]:查无此人!!!")
elif command == 4:
# 查询操作
findName = input("请输入要查询的人员姓名:")
for user in userList:
if findName in user:
print("[INFO]:查询成功,人员信息如下:", end="\t")
print(user)
break
else:
print("[INFO]:查无此人!!!")
elif command == 5:
# 查询所有
admin = input("请输入管理员密码:")
if admin == password:
for user in userList:
print(user)
else:
print("[ERROR]:密码不正确!!!")
elif command == 6:
print("[INFO]:谢谢使用,再见!!!")
break
else:
print("[ERROR]:输入错误,请重新输入:")

三、元组

1、元组的格式:

        python的元组与列表类似,不同之处在于元组的元素不能修改,元组使用小括号,列表使用方括号
tuple = (元素,元素,元素,元素)

2、元组的使用:

"""
元组的创建
"""
# 方式1 : 使用range函数创建元组
t1 = tuple(range(10,20,2))
print(t1) # (10, 12, 14, 16, 18)

# 方式2 : 直接创建元组
t2 = (10,12,14,16)
print(t2) # (10, 12, 14, 16)
# 如果只有一个元素,创建方式如下
t3 = (100,) # 如果(100)这样写,则t3会变成 int 型的数,需要在后面加,号才是元组
print(t3) # (100,)

"""
元组的查询
index(str) : 返回指定元素的下标,如果没有,则报错
"""
t5 = (100,200,300,[10,20,30],"hello world")
print(t5.index("hello world")) # 4

# 注意:元组的元素不可以修改,但是如果元组中的列表的元素是可以修改的,因为列表修改完之后id没有变化

"""
元组的统计
count(str) : 返回指定元素的个数,如果没有,则返回0
"""
t6 = (1,2,3,4,5,6,7)
print(t6.count(3)) # 1

四、字典

1、字典的介绍

dict = {key1:value1, key1:value1, key3:value3, ...}
"""
字典和列表一样,可以存储多个数据
字典中找某个元素时同过key值进行查找,返回的是value值,如果没有key,则报错
字典的key值一般多为字符串
"""

2、字典的创建

"""
1.创建字典
"""
numDict = {} # 创建一个空的字典
print(numDict.fromkeys(["a","c","d"],10)) # 第一个参数是一个序列,第二个参数是固定值
# 打印结果是:{'a': 10, 'c': 10, 'd': 10}

3、字典的添加、修改、查询

"""
字典数据的添加、修改和获取
"""
# 1.根据键名添加或者修改数据
userDict = {}
print(userDict) # {}

userDict["name"] = "zhangsan" # 如果字典中有name这个key,则修改,没有name这个key,则添加新的键值对
print(userDict) # {'name': 'zhangsan'}

userDict['name'] = "lisi" # 字典中有key为name的键,因此修改数据
print(userDict) # {'name': 'lisi'}

# ⭐⭐⭐⭐⭐2.通过 setdefault(key,value) 方法进行添加或者修改数据
# setdefault(key) 该方法通过key去获取value
# 如果有key,则返回value的值,
# 如果没有key,则创建key,并将value设置为None
# setdefault(key,value) : 该方法如果字典中没有key值,则创建 key:value 键值对
# 如果有key值,则不管value,直接返回字典中key对应的值
value = userDict.setdefault("name") # userDict中有key为name的键值对,因此返回name对应的value
print(value) # lisi
value = userDict.setdefault("age") # userDict中没有key为age的键值对,此时将创建新的键值对:age:None
print(userDict) # {'name': 'lisi', 'age': None}

# ⭐⭐⭐⭐⭐3. keys() : 返回字典中所有key的列表
keysList = userDict.keys()
print(keysList) # dict_keys(['name', 'age'])
print(list(keysList)) # ['name', 'age']

if "name" in userDict.keys():
name = userDict["name"]
print("name存在在字典中,且对应的值为:%s"%name) # name存在在字典中,且对应的值为:lisi
else:
print("name不存在在字典中")

# 4. values() : 返回字典中所有value的列表
valueList = userDict.values();
print(valueList) # dict_values(['lisi', None])
print(list(valueList)) # ['lisi', None]

for value in userDict.values():
print(value,end="\t") # lisi None

# ⭐⭐⭐⭐⭐5.items() : 该方法返回字典中所有的(key,value)的键值对集合(以元组列表的形式放回)
key_valueList = userDict.items()
print(key_valueList) # dict_items([('name', 'lisi'), ('age', None)])
print(list(key_valueList)) # [('name', 'lisi'), ('age', None)]

for key,value in key_valueList:
print(key,value, end="\t") # name lisi age None

# 6. get(key,default) : 获取指定的键的值,如果没有这个键,则返回
userDict = {'id': 'it001', 'name': '司马老贼', 'age': 22, 'gender': '男'}
print(userDict.get("id")) # it001
print(userDict.get("address")) # None
print(userDict.get("type","妖族")) # 妖族

if userDict.get("type"):
print("种族是:%s"%(userDict.get("type")))
else:
print("没有type这个key")

# 7. update(dict) : 替换或者新增key的值。
# 即参数dict中有调用update方法的字典中的key,则将参数dict中的key对应的value值存放到调用update方法的key中
# 如果调用update方法的字典对象中没有参数dict对应的key,则将dict中对应的key:value添加到调用方法的字典中
userDict = {'id': 'it001', 'name': '司马老贼', 'age': 22, 'gender': '男'}
dict = {"name":"司马懿", "type":"魏国"}
userDict.update(dict)
print(userDict) # {'id': 'it001', 'name': '司马懿', 'age': 22, 'gender': '男', 'type': '魏国'}

4、字典的拷贝和删除

"""
字典数据的拷贝和删除
"""

dict = {"id":"it001","name":"貂蝉","age":18,"gender":"女"}

# 1.字典数据的拷贝: copy() : 深拷贝,生成一个新的字典
newDict = dict.copy()
print(id(dict)) # 2142753487464
print(id(newDict)) # 2142753487536
print(newDict) # {'id': 'it001', 'name': '貂蝉', 'age': 18, 'gender': '女'}

# 2. pop(key) : 根据key删除字典数据,并返回 key 对应的 value 值
# 删除的是 key 和 value ,如果没有对应的 key,则报错
# pop(key,default) : 根据key删除对应的key:value,返回value值,如果没有key,返回默认值default
print(newDict.pop("name")) # 貂蝉
print(newDict) # {'id': 'it001', 'age': 18, 'gender': '女'}
print(newDict.pop("aaa","没有这个key")) # 没有这个key

# 3. popitem() : 从后向前依次删除一个字典中的key:value键值对,并返回删除的键值对的元组
print(newDict.popitem()) # ('gender', '女')
key, value = newDict.popitem() # 此种写法python中叫做拆包,即将(key,value) 分别赋值给对应位置上的变量
print(key) # age
print(value) # 18

keysList = []
valuesList = []
for i in range(len(dict)):
key, value = dict.popitem()
keysList.append(key)
valuesList.append(value)
print(keysList) # ['gender', 'age', 'name', 'id']
print(valuesList) # ['女', 18, '貂蝉', 'it001']

# 4. clear() : 清空字典数据,但不删除字典
dict1 = dict.copy()
dict1.clear()
print(dict1) # {}

# 5. del() : 删除字典
dict2 = dict.copy()
del(dict2)
print(dict2) # 报错

5、字典推导式的使用

"""
字典推导式
"""
numDict = {i: i ** 2 for i in range(1, 11)} # 对返回的数据进行处理为键值对
print(numDict) # {1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81, 10: 100}

# 1.将两个列表合并为一个字典
keysList = ["id", "name", "age", "gender"]
valuesList = ["it001", "司马老贼", 22, "男"]
userDict = {keysList[i]: valuesList[i] for i in range(len(keysList))}
print(userDict) # {'id': 'it001', 'name': '司马老贼', 'age': 22, 'gender': '男'}

# 2.将字典转换为两个列表,分别存储key和value
keysList = []
valuesList = []
userDict = {'id': 'it001', 'name': '司马老贼', 'age': 22, 'gender': '男'}
for key, value in userDict.items():
keysList.append(key)
valuesList.append(value)
print(keysList) # ['id', 'name', 'age', 'gender']
print(valuesList) # ['it001', '司马老贼', 22, '男']

# 3.将字典数据的key和value互相转换
userDict = {'id': 'it001', 'name': '司马老贼', 'age': 22, 'gender': '男'}
newDuserDict = {value: key for key, value in userDict.items()}
print(newDuserDict) # {'it001': 'id', '司马老贼': 'name', 22: 'age', '男': 'gender'}

6、练习

(1)、使用字典统计一个字符串中各个字符出现的个数
"""
使用字典统计一个字符串中各个字符出现的次数
"""
str1 = "ahusagwiugaslkghasgiasgdfkhpqrgasgdh"
numDict = {}
for s in str1:
if s not in numDict.keys(): # 如果字典里的keys没有这个s,就表示第一次拿到这个s
numDict[s] = 1 # 将s代表的字符放入字典中,并设置个数为1
# numDict.setdefault(s,1) 用setdefault(key,value) 这个方法效果同上
else:
numDict[s] += 1 # 如果有这个s代表的字符,则将数量+1
print(numDict)
# 结果:{'a': 6, 'h': 4, 'u': 2, 's': 5, 'g': 7, 'w': 1, 'i': 2, 'l': 1, 'k': 2, 'd': 2, 'f': 1, 'p': 1, 'q': 1, 'r': 1}

五、set集合

1、set集合介绍

集合、列表、元组之间是可以相互转换的。
集合的每个数据都是唯一的,没有重复的数据。
集合和字典一样,元素都是无序的。

2、集合的操作

"""
1.创建集合 set()
"""
# 普通创建方式
numSet = set() # 创建一个空集合
print(type(numSet)) # <class 'set'>

# 利用集合快速去除列表中的重复元素
numList = [10, 20, 45, 10, 48, 0, 41, 10, 0, 95, 23, 25, 75]
numSet = set(numList)
print(numSet) # {0, 41, 10, 75, 45, 48, 20, 23, 25, 95}
numList = list(set(numList)) # 先使用set(list) 将列表转换为set集合,会自动去重,然后再用list(set),将集合转换为列表
print(numList) # [0, 41, 10, 75, 45, 48, 20, 23, 25, 95]

# 利用集合推导式创建集合
set1 = {i for i in range(1,5,1)}
set2 = {i for i in range(1,6,2)}
print(set1) # {1, 2, 3, 4}
print(set2) # {1, 3, 5}

"""
2. 添加数据
"""
# (1). add() : 向集合中添加一个数据
numSet = {0, 41, 10, 75, 45, 48, 20, 23, 25, 95}
numSet.add(100)
print(numSet) # {0, 100, 41, 10, 75, 45, 48, 20, 23, 25, 95}

# (2). update(list) : 向集合中添加多条数据(参数是一个列表,把列表中的没个元素都添加到集合中)
numSet.update([101,102,103])
print(numSet) # {0, 100, 101, 102, 103, 41, 10, 75, 45, 48, 20, 23, 25, 95}

"""
3. 删除数据
"""
# (1). remove(arg) : 删除指定的数据,如果没有要删除的数据,则报错
numSet = {0, 41, 10, 75, 45, 48, 20, 23, 25, 95}
numSet.remove(0)
print(numSet) # {41, 10, 75, 45, 48, 20, 23, 25, 95}

# (2). discard(arg) : 删除指定的数据,如果没有要删除的数据,则不做任何操作
numSet = {0, 41, 10, 75, 45, 48, 20, 23, 25, 95}
numSet.discard(41)
print(numSet) # {0, 10, 75, 45, 48, 20, 23, 25, 95}
numSet.discard(6000)
print(numSet) # {0, 10, 75, 45, 48, 20, 23, 25, 95}

# (3). pop(arg) : 删除集合中的数据,默认从前向后删除,每次删除一个,返回删除的数据
numSet = {0, 41, 10, 75, 45, 48, 20, 23, 25, 95}
num = numSet.pop();
print(num) # 0
print(numSet) # {41, 10, 75, 45, 48, 20, 23, 25, 95}

######### 如果有需要进行复杂操作,一般集合都会转为列表进行复杂操作,完成操作之后再转回集合

"""
4.集合的其他操作
"""
set1 = {1, 2, 3, 4}
set2 = {1, 3, 5}
# 交集 :两个集合共同的元素
print(set1 & set2) # {1, 3}

# 并集:合并两个集合,并去除重复元素
print(set1 | set2) # {1, 2, 3, 4, 5}

# 差集:
print(set1 - set2) # {2, 4} : set1有,set2没有的元素
print(set2 - set1) # {5} :set2有,set1没有的元素

六、字符串、列表、元组、集合、字典等具有的公共方法

1、运算符



注意:in对字典进行判断时,判断的是字典的key值

2、python内置函数

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐