- 写在前面:这几篇博客就作为自己的一个学习笔记记录,涉及的内容仅供参考,若有不当之处,麻烦各位大佬指正
Tupls(元组)
元组是用来在单个变量中存储多个元素
元组是python中用于存储数据集合的4中内置数据类型之一(其它三种是list set dictionary)
- 示例
thistuple = ("apple", "banana", "cherry")
print(thistuple)
# ('apple', 'banana', 'cherry')
类型
<class 'tuple'>
特点
- 元组是有序,不可改变,允许重复值的
- 元组存在索引(可以通过索引访问元素)
- 支持任意数据类型,并且可以包含不同的数据类型
注意:
当元组中只存在一项元素时,必须在该元素后面添加一个逗号,否则无法识别为元组类型
thistuple = ("apple",)
print(type(thistuple))
# <class 'tuple'>
#NOT a tuple
thistuple = ("apple")
print(type(thistuple))
# <class 'str'>
tuple()构造函数
使用tuple()构造函数创建元组
thistuple = tuple(("apple", "banana", "cherry"))
# note the double round-brackets
print(thistuple)
# ('apple', 'banana', 'cherry')
如何更换元组值(增加/删除/修改)
上面提到创建元组后无法更改元素的值,所以此时可以和列表进行结合,先将元组转换为列表,再对其中元素进行操作(增/删/改),然后将列表转换为元组
示例:修改
x = ("apple", "banana", "cherry") # tuple
y = list(x) # list
y[1] = "kiwi"
x = tuple(y)
print(x)
# ("apple", "kiwi", "cherry")
打包/解包是什么
“打包”:创建一个元组时,通常会对其进行分配值,这个过程叫做”打包“
fruits = ("apple", "banana", "cherry")
“解包”:允许将值提取回变量中
fruits = ("apple", "banana", "cherry")
(green, yellow, red) = fruits
print(green)
print(yellow)
print(red)
注意:当变量的数量与 元组中值的数量不匹配时,必须使用 ’*‘号将剩余的值设置为列表
- 注意此时*号位于最后一个元素前面
fruits = ("apple", "banana", "cherry", "strawberry", "raspberry")
#此时括号中变量数量于元组中值数量不匹配,使用 *号进行设置
(green, yellow, *red) = fruits
print(green)
print(yellow)
print(red)
'''apple
banana
['cherry', 'strawberry', 'raspberry']
'''
- 将*号放置于中间时,会将中间这个元素设置列表,然后直到剩余元素与元组中剩余值相匹配
fruits = ("apple", "mango", "papaya", "pineapple", "cherry")
(green, *tropic, red) = fruits
print(green)
print(tropic)
print(red)
'''
apple
['mango', 'papaya', 'pineapple']
cherry
'''
如何遍历索引
使用range()函数和len()方法创建索引号对元组进行遍历
- 注意:在python2中range()函数创建了一个整数列表,在python3中返回一个可迭代对象
- len() : 返回对象(字符/列表/元组等)的长度或者项目个数
thistuple = ("apple", "banana", "cherry")
for i in range(len(thistuple)):
print(thistuple[i])
元组操作
元组支持 + 运算
tuple1 = ("a", "b" , "c")
tuple2 = (1, 2, 3)
tuple3 = tuple1 + tuple2
print(tuple3)
# ('a', 'b', 'c', 1, 2, 3)
元组支持 * 运算
fruits = ("apple", "banana", "cherry")
mytuple = fruits * 2
print(mytuple)
# ('apple', 'banana', 'cherry', 'apple', 'banana', 'cherry')
count()方法与index()方法
- count()方法: 统计字符串中某个字符出现的次数
str.count(sub, start= 0,end=len(string))
- sub – 搜索的子字符串
- start – 字符串开始搜索的位置。默认为第一个字符,第一个字符索引值为0。
- end – 字符串中结束搜索的位置。字符中第一个字符的索引为 0。默认为字符串的最后一个位置。
返回值:返回该子字符串出现的次数
thistuple = ("apple", "banana", "cherry","apple","apple")
src = "apple"
print(thistuple.count(src)) # 3
print(thistuple.count("banana")) # 1
- index()方法:用于从列表中查找某个值的索引位置
list.index(x[, start[, end]])
- x-- 查找的对象。
- start-- 可选,查找的起始位置。
- end-- 可选,查找的结束位置。
返回值:返回查找对象的索引位置,若没有找到对象则抛出异常
注意:默认是找第一个出现位置
list = ["apple", "banana", "cherry"]
src = "banana"
print(list.index(src)) # 1
Sets(集合)
构造
示例:
thisset = {"apple", "banana", "cherry"}
print(thisset)
或者使用构造函数set()
thisset = set(("apple", "banana", "cherry"))
print(thisset)
注意:由于sets是无序的,所以在输出的时候是顺序是随机的
类型
<class 'set'>
特点
- 无序,不可更改(可以添加),不允许重复值
注意:出现重复值则后出现的将被忽略
thisset = {"apple", "banana", "cherry", "apple"}
print(thisset) # {'banana', 'cherry', 'apple'}
如何添加
- 使用add()方法添加项目
thisset = {"apple", "banana", "cherry"}
thisset.add("orange")
print(thisset)
- 使用update()方法将另一个集合中的项目添加到当前集合中
thisset = {"apple", "banana", "cherry"}
tropical = {"pineapple", "mango", "papaya"}
thisset.update(tropical)
print(thisset)
注意:update()方法中的对象不一定是sets,可以是任何可迭代对象(元组,列表等)
- 使用union()方法返回一个包含两个sets的新集合
set1 = {"a", "b" , "c"}
set2 = {1, 2, 3}
set3 = set1.union(set2)
print(set3)
注意: 当存在重复项时,update()和union()会去除重复项
如何删除
使用remove()或者discard()方法或者pop()方法
- 使用remove()方法
thisset = {"apple", "banana", "cherry"}
thisset.remove("banana")
print(thisset)
注意: remove()方法删除项目时,如果删除的项目不存在则会报错,但是使用discard()方法若不存在则不会报错
- 使用discard()方法
thisset = {"apple", "banana", "cherry"}
thisset.discard("banana")
print(thisset)
- 使用pop()方法,删除sets中最后一项
注意:使用pop()方法删除项目时,由于sets是随机的所以不能确认删除的是那一项
thisset = {"apple", "banana", "cherry"}
x = thisset.pop()
print(x)
print(thisset)
保留重复项
- 使用intersection_update()方法只保留重复项
x = {"apple", "banana", "cherry"}
y = {"google", "microsoft", "apple"}
x.intersection_update(y)
- 使用intersection()方法将返回一个新集合,该集合中存在两个集合中都存在的项目
x = {"apple", "banana", "cherry"}
y = {"google", "microsoft", "apple"}
z = x.intersection(y)
不保存重复项
- 使用symmetric_difference_update()方法保存非重复项
x = {"apple", "banana", "cherry"}
y = {"google", "microsoft", "apple"}
x.symmetric_difference_update(y)
- 使用symmetric_difference()方法返回一个保存非重复项的集合
x = {"apple", "banana", "cherry"}
y = {"google", "microsoft", "apple"}
z = x.symmetric_difference(y)
清空Sets
使用clear()方法/del关键字 清空集合
thisset = {"apple", "banana", "cherry"}
thisset.clear()
print(thisset)
使用del关键字删除Sets
thisset = {"apple", "banana", "cherry"}
del thisset
print(thisset)
Set内置方法
方法 | 描述 |
add() | 为集合添加元素 |
clear() | 移除集合中的所有元素 |
copy() | 拷贝一个集合 |
difference() | 返回多个集合的差集 |
difference_update() | 移除集合中的元素,该元素在指定的集合也存在。 |
discard() | 删除集合中指定的元素 |
intersection() | 返回集合的交集 |
intersection_update() | 返回集合的交集。 |
isdisjoint() | 判断两个集合是否包含相同的元素,如果没有返回 True,否则返回 False。 |
issubset() | 判断指定集合是否为该方法参数集合的子集。 |
issuperset() | 判断该方法的参数集合是否为指定集合的子集 |
pop() | 随机移除元素 |
remove() | 移除指定元素 |
symmetric_difference() | 返回两个集合中不重复的元素集合。 |
symmetric_difference_update() | 移除当前集合中在另外一个指定集合相同的元素,并将另外一个指定集合中不同的元素插入到当前集合中。 |
union() | 返回两个集合的并集 |
update() | 给集合添加元素 |
Dictionaries(字典)
Dictionaries用于在键值对中存储数据值
示例
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
类型
<class 'dict'>
特点
- 有序,可改变,不允许重复的集合
- 每个字典项按照键值对的形式体现,可以通过键名进行引用
注意:字典是无序的,后面重复项会将前面出现的项进行覆盖
如何访问字典中的值
- 通过 [key] 来访问字典中的值
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = thisdict["model"]
- 通过get()方法
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = thisdict.get("model") # Mustang
获取字典中所有key
通过** keys() **方法返回字典中所有键的列表
返回类型:
<class 'dict_keys'>
示例:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = thisdict.keys()
# dict_keys(['brand', 'model', 'year'])
print(x)
获取字典中的值
通过**values()**方法将返回字典中的所有值的列表
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = thisdict.values()
获取键值对列表
通过**items()**方法获取键值对列表
返回类型:<class ‘dict_items’>
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = thisdict.items()
# dict_items([('brand', 'Ford'), ('model', 'Mustang'), ('year', 1964)])
更改指定项(增/删/改)
如何修改
- 通过引用键名来修改指定值
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict["year"] = 2018
- 通过update()方法更新字典,参数为字典或者具有键值对的可迭代对象
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.update({"year": 2020})
如何增加
- 通过使用新的索引键并且对其进行分配值添加到字典中
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict["color"] = "red"
print(thisdict)
- 通过update()方法更新字典,若项目不存在则添加该项目。参数为字典或者具有键值对的可以迭代的对象
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.update({"color": "red"})
如何删除
- pop()方法删除指定键的项
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.pop("model")
print(thisdict)
- popitem()方法删除最后插入的项目(3.7版本前随机删除)
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.popitem()
print(thisdict)
- del关键字删除指定键对应的项,也可以通过del关键字删除整个字典
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
del thisdict["model"]
print(thisdict)
# del thisdict
- clear()方法清空字典
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.clear()
print(thisdict) # {}
复制字典
- 通过内置方法copy()
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
mydict = thisdict.copy()
print(mydict)
- 使用内置函数dict()
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
mydict = dict(thisdict)
print(mydict)
嵌套字典
创建:
myfamily = {
"child1" : {
"name" : "Emil",
"year" : 2004
},
"child2" : {
"name" : "Tobias",
"year" : 2007
},
"child3" : {
"name" : "Linus",
"year" : 2011
}
}
或者创建三个单独的字典,然后合并到其中一个字典中(相当于赋值给了新字典)
在这里插入代码片child1 = {
"name" : "Emil",
"year" : 2004
}
child2 = {
"name" : "Tobias",
"year" : 2007
}
child3 = {
"name" : "Linus",
"year" : 2011
}
myfamily = {
"child1" : child1,
"child2" : child2,
"child3" : child3
}
其它点
缩进
python通过缩进来定义代码中的范围(其它语言通常使用大括号)
if 与 elif 与 else
python中引入了elif关键字
elif:如果前面的条件是不正确的,继续执行这条语句
- 为什么引入elif?
如果全部使用if,运行时会执行所有if语句,如果使用if-elif,在运行的时候,如果某个if或者elif满足True,则跳出判断,效率更高
注意:一个if语句中可以包含多个elif语句,但是只能有一个else语句
嵌套if
x = 41
if x > 10:
print("Above ten,")
if x > 20:
print("and also above 20!")
else:
print("but not above 20.")
and关键字
and关键字是一个逻辑运算符,用于条件语句结合
a = 1
b = 2
c = 3
if c > a and c > b:
print("True")
or关键字
a = 1
b = 2
c = 3
if c > a or c > b
print("True")
pass
if语句不能为空,当if语句为空时,添加pass
x = 1
y = 2
if x > y:
pass
else
当条件不为真时,跳出判断循环
- 注意:python中else可以和while一起使用
i = 1
while i < 6:
print(i)
i += 1
else:
print("i is no longer less than 6")
- 注意:也可以与for循环一起使用
# 打印0-5数字,在跳出循环时打印
for x in range(6):
print(x)
else:
print("Finally finished!")
- 注意:当循环被break打断,那么else语句则不会执行
for
for支持对列表,元组,字典,一组/一个字符串进行迭代
python中的for关键字,像是一种迭代器进行遍历
range()函数
用于循环一组代码指定的次数
range()中定义范围,若为一个数字则表示从0开始,递增的顺序结束在指定数字位置(不包括该位置)
示例:
for x in range(2, 6):
print(x) # 2 3 4 5
注意print()函数默认换行可以看一下源码 ”源码中写入了\n“
函数
在python文档中,函数通常被称为args
定义函数
通过def关键字
def my_func()
print('hello')
如何接收任意参数
当参数数量可变时,在函数中定义的参数前面添加一个 * ,之后该函数将会接收一个