Python基础-python语言基础

第1章 注释

  • 单行行注释:# 被注释内容
  • 多行注释:”’被注释内容”’,或者”””被注释内容”””(三个单引号或三个双引号)

第2章 变量

2.1 变量是什么?

变量是把程序运行的中间结果临时的存在内存里,以便后续的代码调用。

2.2 变量定义的规则

  1. 变量名只能是字母、数字或下划线的任意组合;
  2. 变量名的第一个字符不能是数字;
  3. 以下关键字不能声明为变量名:

[‘and’, ‘as’, ‘assert’, ‘break’, ‘class’, ‘continue’, ‘def’, ‘del’, ‘elif’, ‘else’, ‘except’, ‘exec’, ‘finally’, ‘for’, ‘from’, ‘global’, ‘if’, ‘import’, ‘in’, ‘is’, ‘lambda’, ‘not’, ‘or’, ‘pass’, ‘print’, ‘raise’, ‘return’, ‘try’, ‘while’, ‘with’, ‘yield’]

  1. 变量的定义要具有可描述性。

2.3 推荐定义方式

# 驼峰体
AgeOfLeon = 56
NumberOfStudents = 80

#下划线
age_of_leon = 56
number_of_students = 80

2.4 定义变量不好的方式举例

  1. 变量名为中文、拼音
  2. 变量名过长
  3. 变量名词不达意

2.5 声明变量

#!/usr/bin/env python
# -*- coding: utf-8 -*-
  
name = "leonshadow"

第3章 常量

常量即指不变的量,如pai 3.141592653…, 或在程序运行过程中不会改变的量。在Python中没有一个专门的语法代表常量,程序员约定俗成用变量名全部大写代表常量AGE_OF_LEON= 56

Tips:在c语言中有专门的常量定义语法,const int count = 60; 一旦定义为常量,更改即会报错。

第4章 数据类型

4.1 数据类型划分

4.1.1 可变数据类型和不可变数据类型

  • 可变数据类型(不可哈希):list,dict,set
  • 不可变数据类型(可哈希):元组,bool,int,str

4.2 整类型(int)

主要用于计算(1,2,3….)。

4.2.1 bit_length方法

【功能】:

计算该数字的二进制数字的位数

【示例】:

i = 0
while i <= 10:
    print(i.bit_length())
i+=1

【结果】:

D:\WorkSpace\Python\venv\Scripts\python.exe D:/WorkSpace/python_study/week05/数据类型01.py
0
1
2
2
3
3
3
3
4
4
4

Process finished with exit code 0

4.3 布尔类型(bool)

主要用于判断(TRUE,FLASE)。

4.4 字符串类型(str)

主要用于存储少量数据并进行操作(’abc’,’张三’,’123’…)。

4.4.1 字符串切片

Tips:字符串切片“顾首不顾尾”
s = 'ABCDLSESRF'

【示例】:取第一个字符

s1 = s[0]
print(s1)

【示例】:取第三个字符

s2 = s[2]
print(s2)

【示例】:取最后一个个字符

s3 = s[-1]
print(s3)

【示例】:取倒数第二个字符

s4 = s[-2]
print(s4)

【示例】:取第一个到第四个字符

s5 = s[0:4]
print(s5)

【示例】:取第一个到最后一个字符(不含最后一个字符)

s6 = s[0:-1]
print(s6)

【示例】:取第一个到最后一个字符(含最后一个字符)

s7 = s[:]
s8 = s[0:]
print(s7,s8)

【示例】:隔一个取一个字符(步长为2

s10 = s[0:5:2]
print(s10)

【示例】:从后往前取(步长为2

s11 = s[4:0:-1]
print(s11)
s13 = s[3::-2]
print(s13)

【示例】:倒着取所有字符

s14 = s[-1::-1]
print(s14)
s15 = s[::-1]
print(s15)

4.4.2 capitalize方法

【功能】:

首字母大写。

【示例】:

s = 'alexWUsir'
print(s1)

【结果】:

D:\WorkSpace\Python\venv\Scripts\python.exe D:/WorkSpace/python_study/week05/数据类型01.py
Alexwusir

Process finished with exit code 0

4.4.3 upper/lower方法

【功能】:

字母全大写/全小写

【示例】:

s = 'alexWUsir'
print(s.upper())
print(s.lower())

【结果】:

D:\WorkSpace\Python\venv\Scripts\python.exe D:/WorkSpace/python_study/week05/数据类型01.py
ALEXWUSIR
alexwusir

Process finished with exit code 0

【应用】:输入验证码

s_str= 'acEQ1'
you_input =input('请输入验证码,不区分大小写: ')
if s_str.upper() == you_input.upper():
    print('输入成功')
else:
    print('请重新输入')

【结果】:

D:\WorkSpace\Python\venv\Scripts\python.exe D:/WorkSpace/python_study/week05/数据类型01.py
请输入验证码,不区分大小写: aceq1
输入成功

Process finished with exit code 0

4.4.4 swapcase方法

【功能】:

大小写翻转

【示例】:

s = 'alexWUsir'
print(s.upper())
print(s.lower())

【结果】:

D:\WorkSpace\Python\venv\Scripts\python.exe D:/WorkSpace/python_study/week05/数据类型01.py
ALEXWUSIR
alexwusir

Process finished with exit code 0

4.4.5 title方法

【功能】:

按照标题的方式转换字符串,每个隔开(特殊字符或者数字)的单词首字母大写

【示例】:

s1 = 'alex*egon-wusir'
s2 = 'fade,crazy*w4rri0r_songsong node_3'
print(s1.title())
print(s2.title())

【结果】:

D:\WorkSpace\Python\venv\Scripts\python.exe D:/WorkSpace/python_study/week05/数据类型01.py
Alex*Egon-Wusir
Fade,Crazy*W4Rri0R_Songsong Node_3

Process finished with exit code 0

4.4.6 center方法

【功能】:

字符串居中,默认以空格填充空白

【示例】:

s = 'alexWUsir'
print(s.center(20))
print(s.center(20,'#'))

【结果】:

D:\WorkSpace\Python\venv\Scripts\python.exe D:/WorkSpace/python_study/week05/数据类型01.py
     alexWUsir     
#####alexWUsir######

Process finished with exit code 0

4.4.7 expandtabs方法

【功能】:

以指定的字符数显示tab符号(\t),可以用来格式化输出表格

【示例】:

s = 'name\tage\thobby\nzhangsan\t16\tbasketball\nlisi\t30\tfootball'
print(s.expandtabs(20))

【结果】:

D:\WorkSpace\Python\venv\Scripts\python.exe D:/WorkSpace/python_study/week05/数据类型01.py
name                age                 hobby
zhangsan            16                  basketball
lisi                30                  football

Process finished with exit code 0

4.4.8 len方法

【功能】:

计算字符串中字符的数量

【示例】:

s = 'alex二哥'
print(len(s))

【结果】:

D:\WorkSpace\Python\venv\Scripts\python.exe D:/WorkSpace/python_study/week05/数据类型01.py
6

Process finished with exit code 0

4.4.9 startswith/endswith方法

【功能】:

判断是否以什么字符串开头/结尾

【示例】:

s = 'alexWUsir'
print(s.startswith('alex'))
print(s.startswith('e',2,5))

【结果】:

D:\WorkSpace\Python\venv\Scripts\python.exe D:/WorkSpace/python_study/week05/数据类型01.py
True
True

Process finished with exit code 0

4.4.10 find/index方法

【功能】:

通过元素找索引,找不到返回-1,index通过元素找索引,找不到报错

【示例】:

s = 'alexWUsir'
print(s.find('A'))
print(s.index('e'))

【结果】:

D:\WorkSpace\Python\venv\Scripts\python.exe D:/WorkSpace/python_study/week05/数据类型01.py
-1
2

Process finished with exit code 0

4.4.11 strip/rstrip/lstrip方法

【功能】:

去除头尾/右侧/左侧的指定的字符,默认为空格

【示例】:

s = ' *a%lexWUsi* r%'
print(s.lstrip(' *%'))
print(s.rstrip(' *%'))
print(s.strip(' *%'))

【结果】:

D:\WorkSpace\Python\venv\Scripts\python.exe D:/WorkSpace/python_study/week05/数据类型01.py
a%lexWUsi* r%
 *a%lexWUsi* r
a%lexWUsi* r

Process finished with exit code 0

4.4.12 count方法

【功能】:

统计字符串出现的次数

【示例】:

s = 'alexaa wusirl'
print(s.count('al'))

【结果】:

D:\WorkSpace\Python\venv\Scripts\python.exe D:/WorkSpace/python_study/week05/数据类型01.py
1

Process finished with exit code 0

4.4.13 split方法

【功能】:

以指定的字符分割字符串为列表

【示例】:

s = ';alex;wusir;taibai'
print(s.split(';'))

【结果】:

D:\WorkSpace\Python\venv\Scripts\python.exe D:/WorkSpace/python_study/week05/数据类型01.py
['', 'alex', 'wusir', 'taibai']

Process finished with exit code 0

4.4.14 replace方法

【功能】:

替换指定的字符串内容,默认替换所有

【示例】:

s = 'abcdefghijkabcdefghijk'
print(s.replace('a','z'))
print(s.replace('a','z',1))

【结果】:

D:\WorkSpace\Python\venv\Scripts\python.exe D:/WorkSpace/python_study/week05/数据类型01.py
zbcdefghijkzbcdefghijk
zbcdefghijkabcdefghijk

Process finished with exit code 0

4.4.15 is系列方法

【功能】:

isalnum():字符串由字母或数字组成

isalpha():字符串只由字母组成

isdigit():字符串只由数字组成

【示例】:

s = 'alexWUsir'
print(s.isalnum())
print(s.isalpha())
print(s.isdigit())

【结果】:

D:\WorkSpace\Python\venv\Scripts\python.exe D:/WorkSpace/python_study/week05/数据类型01.py
True
True
False

Process finished with exit code 0

4.5 列表类型(list)

主要储存大量的数据([1,2,3,’张三’,’abc’,[1,2,3]])

4.5.1 append方法

【功能】:

追加列表元素到最后

【示例】:

li = ['alex','wusir','leon','张三','shadow']
li.append('李四')
print(li)

【结果】:

D:\WorkSpace\Python\venv\Scripts\python.exe D:/WorkSpace/python_study/week05/数据类型02.py
['alex', 'wusir', 'leon', '张三', 'shadow', '李四']

Process finished with exit code 0

4.5.2 instert方法

【功能】:

插入列表元素到指定的索引位置

【示例】:

li = ['alex','wusir','leon','张三','shadow']
li.insert(4,'王五')
print(li)

【结果】:

D:\WorkSpace\Python\venv\Scripts\python.exe D:/WorkSpace/python_study/week05/数据类型02.py
['alex', 'wusir', 'leon', '张三', '王五', 'shadow']

Process finished with exit code 0

4.5.3 extend方法

【功能】:

迭代插入元素到列表,默认插入到列表最后

【示例】:

li = ['alex','wusir','leon','张三','shadow']
li.extend('赵六')
print(li)

【结果】:

D:\WorkSpace\Python\venv\Scripts\python.exe D:/WorkSpace/python_study/week05/数据类型02.py
['alex', 'wusir', 'leon', '张三', 'shadow', '赵', '六']

Process finished with exit code 0

4.5.4 pop方法

【功能】:

取出列表中指定索引的元素,默认取出最后一个,返回值为取出的元素

【示例】:

li = ['alex','wusir','leon','张三','shadow']
name = li.pop(2)
print(name,li)
name = li.pop()
print(name,li)

【结果】:

D:\WorkSpace\Python\venv\Scripts\python.exe D:/WorkSpace/python_study/week05/数据类型02.py
leon ['alex', 'wusir', '张三', 'shadow']
shadow ['alex', 'wusir', '张三']

Process finished with exit code 0

4.5.5 remove方法

【功能】:

按元素去删除列表中的元素

【示例】:

li = ['alex','wusir','leon','张三','shadow']
li.remove('leon')
print(li)

【结果】:

D:\WorkSpace\Python\venv\Scripts\python.exe D:/WorkSpace/python_study/week05/数据类型02.py
['alex', 'wusir', '张三', 'shadow']

Process finished with exit code 0

4.5.6 clear方法

【功能】:

清空列表数据

【示例】:

li = ['alex','wusir','leon','张三','shadow']
li.clear()
print(li)

【结果】:

D:\WorkSpace\Python\venv\Scripts\python.exe D:/WorkSpace/python_study/week05/数据类型02.py
[]

Process finished with exit code 0

4.5.7 del方法

【功能】:

删除列表,若列表被删除后,在访问列表会报错

【示例】:

li = ['alex','wusir','leon','张三','shadow']
del li[0:2]
print(li)
del li
print(li)

【结果】:

D:\WorkSpace\Python\venv\Scripts\python.exe D:/WorkSpace/python_study/week05/数据类型02.py
['leon', '张三', 'shadow']
Traceback (most recent call last):
  File "D:/WorkSpace/python_study/week05/数据类型02.py", line 32, in <module>
    print(li)
NameError: name 'li' is not defined

Process finished with exit code 1

4.5.8 修改

【功能】:

直径赋值修改

【示例】:

li = ['alex','wusir','leon','张三','shadow']
li[0] = '123'
print(li)

【结果】:

D:\WorkSpace\Python\venv\Scripts\python.exe D:/WorkSpace/python_study/week05/数据类型02.py
['123', 'wusir', 'leon', '张三', 'shadow']

Process finished with exit code 0

【功能】:

切片修改,相当于将切片的元素删除后将新的数据以元素的方式添加到删除切片的位置中

【示例】:

li = ['alex','wusir','leon','张三','shadow']
li[0:3] = 'abcd1234一二三四'
print(li)

li[1:3] = 'abcd1234一二三四'
print(li)

【结果】:

D:\WorkSpace\Python\venv\Scripts\python.exe D:/WorkSpace/python_study/week05/数据类型02.py
['a', 'b', 'c', 'd', '1', '2', '3', '4', '一', '二', '三', '四', '张三', 'shadow']

Process finished with exit code 0
D:\WorkSpace\Python\venv\Scripts\python.exe D:/WorkSpace/python_study/week05/数据类型02.py
['alex', 'a', 'b', 'c', 'd', '1', '2', '3', '4', '一', '二', '三', '四', '张三', 'shadow']

Process finished with exit code 0

4.5.9 查询操作

【功能】:

直接以索引的方式查询或

【示例】:

li = ['alex','wusir','leon','张三','shadow']
for i in li:
    print(i)

【结果】:

D:\WorkSpace\Python\venv\Scripts\python.exe D:/WorkSpace/python_study/week05/数据类型02.py
alex
wusir
leon
张三
shadow

Process finished with exit code 0

4.5.10 len方法

【功能】:

查询列表中的元素个数

【示例】:

li = ['alex','wusir','leon','张三','shadow']
print(len(li))

【结果】:

D:\WorkSpace\Python\venv\Scripts\python.exe D:/WorkSpace/python_study/week05/数据类型02.py
5

Process finished with exit code 0

4.5.11 count方法

【功能】:

查询列表中指定元素的数量

【示例】:

li = ['alex','wusir','leon','张三','shadow']
print(li.count('leon'))

【结果】:

D:\WorkSpace\Python\venv\Scripts\python.exe D:/WorkSpace/python_study/week05/数据类型02.py
1

Process finished with exit code 0

4.5.12 index方法

【功能】:

查询指定元素所在的索引

【示例】:

li = ['alex','wusir','leon','张三','shadow']
print(li.index('leon'))

【结果】:

D:\WorkSpace\Python\venv\Scripts\python.exe D:/WorkSpace/python_study/week05/数据类型02.py
2

Process finished with exit code 0

4.5.13 sort方法

【功能】:

对列表内元素进行正/反向排序

【示例】:

li = [1,5,4,7,6,2,3]
li.sort()
print(li)
li.sort(reverse=True)
print(li)

【结果】:

D:\WorkSpace\Python\venv\Scripts\python.exe D:/WorkSpace/python_study/week05/数据类型02.py
[1, 2, 3, 4, 5, 6, 7]
[7, 6, 5, 4, 3, 2, 1]

Process finished with exit code 0

4.5.14 reverse方法

【功能】:

对列表内元素反转

【示例】:

li = [1,5,4,7,6,2,3]
li.reverse()
print(li)

【结果】:

D:\WorkSpace\Python\venv\Scripts\python.exe D:/WorkSpace/python_study/week05/数据类型02.py
[3, 2, 6, 7, 4, 5, 1]

Process finished with exit code 0

4.5.15 嵌套列表

【示例】:

li = ['leon','shadow','张三',['alex','李四',89],23]
print(li[1][1])
print(li[3][1])

【结果】:

D:\WorkSpace\Python\venv\Scripts\python.exe D:/WorkSpace/python_study/week05/数据类型02.py
h
李四

Process finished with exit code 0

4.6 tuple类型(元组)

主要储存大量的只读数据((1,2,3,’张三’,))

4.6.1 循环查询

【示例】:

tu = (1,2,3,'alex',[2,3,4,'leon'],'shadow')
for i in tu:
print(i)

【结果】:

D:\WorkSpace\Python\venv\Scripts\python.exe D:/WorkSpace/python_study/week05/数据类型02.py
1
2
3
alex
[2, 3, 4, 'leon']
shadow

Process finished with exit code 0

4.6.2 切片查询

【示例】:

tu = (1,2,3,'alex',[2,3,4,'leon'],'shadow')
print(tu[2:4])

【结果】:

D:\WorkSpace\Python\venv\Scripts\python.exe D:/WorkSpace/python_study/week05/数据类型02.py
(3, 'alex')

Process finished with exit code 0

4.6.3 join方法

【示例】:

li = ['alex','wusir','leon','张三','shadow']
s = ''.join(li)
print(s)
s = '++'.join(li)
print(s)

【结果】:

D:\WorkSpace\Python\venv\Scripts\python.exe D:/WorkSpace/python_study/week05/数据类型02.py
alexwusirleon张三shadow
alex++wusir++leon++张三++shadow

Process finished with exit code 0

4.6.4 range方法(通用)

【功能】:

创建序列

【示例】:

for i in range(3,10):
    print(i)

【结果】:

D:\WorkSpace\Python\venv\Scripts\python.exe D:/WorkSpace/python_study/week05/数据类型02.py
3
4
5
6
7
8
9

Process finished with exit code 0

【示例】:

for i in range(10):
    print(i)

【结果】:

D:\WorkSpace\Python\venv\Scripts\python.exe D:/WorkSpace/python_study/week05/数据类型02.py
0
1
2
3
4
5
6
7
8
9

Process finished with exit code 0

【示例】:

for i in range(0,10,3):
    print(i)

【结果】:

D:\WorkSpace\Python\venv\Scripts\python.exe D:/WorkSpace/python_study/week05/数据类型02.py
0
3
6
9

Process finished with exit code 0

【示例】:

for i in range(10,0,-2):
    print(i)

【结果】:

D:\WorkSpace\Python\venv\Scripts\python.exe D:/WorkSpace/python_study/week05/数据类型02.py
10
8
6
4
2

Process finished with exit code 0

【示例】:

for i in range(10,-1,-2):
    print(i)

【结果】:

D:\WorkSpace\Python\venv\Scripts\python.exe D:/WorkSpace/python_study/week05/数据类型02.py
10
8
6
4
2
0

Process finished with exit code 0

4.7 字典类型(dict)

主要用于存储关系型键值对({‘name’:’张三’,’age’:16},{‘张三’:[],’李四’:[]})。

dict的key必须是不可变数据类型(可哈希),value可以时任意数据类型。

4.7.1 直接增加/修改

【功能】:

没有键值对的时候增加;有键值对的时候则覆盖修改。

【示例】:

dic = {'age': 18, 'name': 'leon', 'sex': 'male',}
dic['high'] = 185           # 增加
print(dic)
dic['age'] = 28             # 覆盖
print(dic)

【结果】:

D:\WorkSpace\Python\venv\Scripts\python.exe D:/WorkSpace/python_study/week05/数据类型03.py
{'age': 18, 'name': 'leon', 'sex': 'male', 'high': 185}
{'age': 28, 'name': 'leon', 'sex': 'male', 'high': 185}

Process finished with exit code 0

4.7.2 setdefault方法

【功能】:

没有相应的键的时候增加,有相应的键的时候不操作

【示例】:

dic = {'age': 18, 'name': 'leon', 'sex': 'male',}
dic.setdefault('weight',150)
print(dic)
dic.setdefault('name','shadow')
print(dic)

【结果】:

D:\WorkSpace\Python\venv\Scripts\python.exe D:/WorkSpace/python_study/week05/数据类型03.py
{'age': 18, 'name': 'leon', 'sex': 'male', 'weight': 150}
{'age': 18, 'name': 'leon', 'sex': 'male', 'weight': 150}

Process finished with exit code 0

4.7.3 pop方法

【功能】:

删除键值对并返回该键的值,同时可设置没有该键的时候的返回值(通常设为None,不设置返回值时报错)

【示例】:

dic = {'age': 18, 'name': 'leon', 'sex': 'male',}
print(dic.pop('name'))
print(dic)
print(dic.pop('height',None))
print(dic)
print(dic.pop('height'))
print(dic)

【结果】:

D:\WorkSpace\Python\venv\Scripts\python.exe D:/WorkSpace/python_study/week05/数据类型03.py
leon
{'age': 18, 'sex': 'male'}
None
{'age': 18, 'sex': 'male'}
Traceback (most recent call last):
  File "D:/WorkSpace/python_study/week05/数据类型03.py", line 27, in <module>
    print(dic.pop('height'))
KeyError: 'height'

Process finished with exit code 0

4.7.4 popitem方法

【功能】:

Python 3.5+版本默认弹出最后一个键值对,Python 3.5及以前版本随机弹出键值对

【示例】:

dic = {'age': 18, 'name': 'leon', 'sex': 'male',}
print(dic.popitem())
print(dic)

【结果】:

D:\WorkSpace\Python\venv\Scripts\python.exe D:/WorkSpace/python_study/week05/数据类型03.py
('sex', 'male')
{'age': 18, 'name': 'leon'}

Process finished with exit code 0

4.7.5 del方法

【功能】:

删除字典

【示例】:

dic = {'age': 18, 'name': 'leon', 'sex': 'male',}
del dic['name']
print(dic)
del dic
print(dic)

【结果】:

D:\WorkSpace\Python\venv\Scripts\python.exe D:/WorkSpace/python_study/week05/数据类型03.py
{'age': 18, 'sex': 'male'}
Traceback (most recent call last):
  File "D:/WorkSpace/python_study/week05/数据类型03.py", line 35, in <module>
    print(dic)
NameError: name 'dic' is not defined

Process finished with exit code 0

4.7.6 clear方法

【功能】:

清空字典

【示例】:

dic = {'age': 18, 'name': 'leon', 'sex': 'male',}
print(dic.clear())
print(dic)

【结果】:

D:\WorkSpace\Python\venv\Scripts\python.exe D:/WorkSpace/python_study/week05/数据类型03.py
None
{}

Process finished with exit code 0

4.7.7 update方法

【功能】:

以update参数中的的字典(dic2)增加/更新调用update方法的的字典(dic1)

【示例】:

dic1 = {'age': 18, 'name': 'leon', 'sex': 'male',}
dic2 = {"name":"alex","weight":75}
dic1.update(dic2)
print(dic1)
print(dic2)

【结果】:

D:\WorkSpace\Python\venv\Scripts\python.exe D:/WorkSpace/python_study/week05/数据类型03.py
{'age': 18, 'name': 'alex', 'sex': 'male', 'weight': 75}
{'name': 'alex', 'weight': 75}

Process finished with exit code 0

4.7.8 get方法

【功能】:

通过键查看相应的值,若没有则返回None或自己指定的值

【示例】:

dic1 = {'age': 18, 'name': 'leon', 'sex': 'male',}
print(dic.get('name'))
print(dic.get('weight'))
print(dic.get('weight','没有这个键'))

【结果】:

D:\WorkSpace\Python\venv\Scripts\python.exe D:/WorkSpace/python_study/week05/数据类型03.py
leon
None
没有这个键

Process finished with exit code 0

4.7.9 查询字典

【功能】:

查询键值对的键、值、键值对

【示例】:

dic = {'age': 18, 'name': 'leon', 'sex': 'male',}
print(dic)
print(dic.keys())
print(dic.values())
print(dic.items())

【结果】:

D:\WorkSpace\Python\venv\Scripts\python.exe D:/WorkSpace/python_study/week05/数据类型03.py
{'age': 18, 'name': 'leon', 'sex': 'male'}
dict_keys(['age', 'name', 'sex'])
dict_values([18, 'leon', 'male'])
dict_items([('age', 18), ('name', 'leon'), ('sex', 'male')])

Process finished with exit code 0

【示例】:

dic = {'age': 18, 'name': 'leon', 'sex': 'male',}
for i in dic:
    print(i)
for i in dic.keys():
    print(i)
for i in dic.values():
    print(i)
for i in dic.items():
    print(i)
for k,v in dic.items():
    print(k,v)

【结果】:

D:\WorkSpace\Python\venv\Scripts\python.exe D:/WorkSpace/python_study/week05/数据类型03.py
age
name
sex

age
name
sex

18
leon
male

('age', 18)
('name', 'leon')
('sex', 'male')

age 18
name leon
sex male

Process finished with exit code 0

【示例】:

dic = {'age': 18, 'name': 'leon', 'sex': 'male',}
v1 = dic['name']
print(v1)
v2 = dic['weight']
print(v2)

【结果】:

D:\WorkSpace\Python\venv\Scripts\python.exe D:/WorkSpace/python_study/week05/数据类型03.py
leon

Traceback (most recent call last):
  File "D:/WorkSpace/python_study/week05/数据类型03.py", line 63, in <module>
    v2 = dic['weight']
KeyError: 'weight'

Process finished with exit code 0

4.7.10 字典嵌套

【示例】:

dic = {
    'name':['alex','wusir','leon'],
    'study':{
        'time':'1812',
        'learn_money':20000,
        'addr':'CBD',
           },
    'age':21
}

dic['age'] = 28
print(dic)
dic['name'].append('shadow')
print(dic)
dic['study']['class'] = 'python'
print(dic)
dic['study']['time'] = '1808'
print(dic)

【结果】:

D:\WorkSpace\Python\venv\Scripts\python.exe D:/WorkSpace/python_study/week05/数据类型03.py
{'name': ['alex', 'wusir', 'leon'], 'study': {'time': '1812', 'learn_money': 20000, 'addr': 'CBD'}, 'age': 28}
{'name': ['alex', 'wusir', 'leon', 'shadow'], 'study': {'time': '1812', 'learn_money': 20000, 'addr': 'CBD'}, 'age': 28}
{'name': ['alex', 'wusir', 'leon', 'shadow'], 'study': {'time': '1812', 'learn_money': 20000, 'addr': 'CBD', 'class': 'python'}, 'age': 28}
{'name': ['alex', 'wusir', 'leon', 'shadow'], 'study': {'time': '1808', 'learn_money': 20000, 'addr': 'CBD', 'class': 'python'}, 'age': 28}

Process finished with exit code 0

4.8 集合类型

主要用于计算交、并、合、差集({1,2,34,’abc’}),集合是可变类型,但是里面的元素必须是不可变类型,集合是无序不重复的。

4.8.1 add方法

【功能】:

向集合中添加一个元素。

【示例】:

set = {'alex', 'wusir', 'leon', 'shadow', 'dashi'}
set.add('saisai')
print(set)

【结果】:

D:\WorkSpace\Python\venv\Scripts\python.exe D:/WorkSpace/Python/python_study/week05/数据类型04.py
{'saisai', 'wusir', 'dashi', 'shadow', 'leon', 'alex'}

Process finished with exit code 0

4.8.2 update方法

【功能】:

以迭代的方式向集合中添加元素。

【示例】:

set = {'alex', 'wusir', 'leon', 'shadow', 'dashi'}
set.update('meinv')
print(set)

【结果】:

D:\WorkSpace\Python\venv\Scripts\python.exe D:/WorkSpace/Python/python_study/week05/数据类型04.py
{'leon', 'shadow', 'm', 'i', 'alex', 'n', 'wusir', 'dashi', 'v', 'e'}

Process finished with exit code 0

4.8.3 pop方法

【功能】:

随机弹出集合中的元素。

【示例】:

set = {'alex', 'wusir', 'leon', 'shadow', 'dashi'}
print(set.pop())
print(set)

【结果】:

D:\WorkSpace\Python\venv\Scripts\python.exe D:/WorkSpace/Python/python_study/week05/数据类型04.py
wusir
{'alex', 'leon', 'shadow', 'dashi'}

Process finished with exit code 0

4.8.4 remove方法

【功能】:

删除集合中指定的元素。

【示例】:

set = {'alex', 'wusir', 'leon', 'shadow', 'dashi'}
set.remove('leon')
print(set)

【结果】:

D:\WorkSpace\Python\venv\Scripts\python.exe D:/WorkSpace/Python/python_study/week05/数据类型04.py
{'alex', 'shadow', 'wusir', 'dashi'}

Process finished with exit code 0

4.8.5 clear方法

【功能】:

清空集合。

【示例】:

set = {'alex', 'wusir', 'leon', 'shadow', 'dashi'}
set.clear()
print(set)

【结果】:

D:\WorkSpace\Python\venv\Scripts\python.exe D:/WorkSpace/Python/python_study/week05/数据类型04.py
set()

Process finished with exit code 0

4.8.6 del方法

【功能】:

删除集合。

【示例】:

set = {'alex', 'wusir', 'leon', 'shadow', 'dashi'}
del set
print(set)

【结果】:

D:\WorkSpace\Python\venv\Scripts\python.exe D:/WorkSpace/Python/python_study/week05/数据类型04.py
<class 'set'>

Process finished with exit code 0

4.8.7 遍历查询

【示例】:

set = {'alex', 'wusir', 'leon', 'shadow', 'dashi'}
for i in set:
    print(i)

【结果】:

D:\WorkSpace\Python\venv\Scripts\python.exe D:/WorkSpace/Python/python_study/week05/数据类型04.py
wusir
alex
shadow
dashi
leon

Process finished with exit code 0

4.8.8 集合的交集

【功能】:

使用 & 或 intersection表示。

【示例】:

set1 = {1, 2, 3, 4, 5}
set2 = {4, 5, 6, 7, 8}
print(set1 & set2)
print(set1.intersection(set2))

【结果】:

D:\WorkSpace\Python\venv\Scripts\python.exe D:/WorkSpace/Python/python_study/week05/数据类型04.py
{4, 5}
{4, 5}

Process finished with exit code 0

4.8.9 集合的合集

【功能】:

使用 | 或者 union表示。

【示例】:

set1 = {1, 2, 3, 4, 5}
set2 = {4, 5, 6, 7, 8}
print(set1 | set2)
print(set2.union(set1))

【结果】:

D:\WorkSpace\Python\venv\Scripts\python.exe D:/WorkSpace/Python/python_study/week05/数据类型04.py
{1, 2, 3, 4, 5, 6, 7, 8}
{1, 2, 3, 4, 5, 6, 7, 8}

Process finished with exit code 0

4.8.10 集合的差集

【功能】:

使用 – 或者 difference表示。

【示例】:

set1 = {1, 2, 3, 4, 5}
set2 = {4, 5, 6, 7, 8}
print(set1 - set2)
print(set1.difference(set2))

【结果】:

D:\WorkSpace\Python\venv\Scripts\python.exe D:/WorkSpace/Python/python_study/week05/数据类型04.py
{1, 2, 3}
{1, 2, 3}

Process finished with exit code 0

4.8.11 集合的反交集

【功能】:

使用 ^ 或者 symmetric_difference 表示。

【示例】:

set1 = {1, 2, 3, 4, 5}
set2 = {4, 5, 6, 7, 8}
print(set1 ^ set2)
print(set1.symmetric_difference(set2))

【结果】:

D:\WorkSpace\Python\venv\Scripts\python.exe D:/WorkSpace/Python/python_study/week05/数据类型04.py
{1, 2, 3, 6, 7, 8}
{1, 2, 3, 6, 7, 8}

Process finished with exit code 0

4.8.12 集合的子集和超集

【功能】:

使用issubset和issuperset表示。

【示例】:

set1 = {1, 2, 3}
set2 = {1, 2, 3, 4, 5, 6}

print(set1 < set2)
print(set1.issubset(set2))      # 这两个相同,都是说明set1是set2子集。

print(set2 > set1)
print(set2.issuperset(set1))    # 这两个相同,都是说明set2是set1超集。

【结果】:

D:\WorkSpace\Python\venv\Scripts\python.exe D:/WorkSpace/Python/python_study/week05/数据类型04.py
True
True
True
True

Process finished with exit code 0

4.8.13 集合去重

【示例】:

li = [1, 1, 2, 2, 3, 3, 4 ,5 ,6 ,7 , 7]
set = set(li)
print(set)
li = list(set)
print(li)

【结果】:

D:\WorkSpace\Python\venv\Scripts\python.exe D:/WorkSpace/Python/python_study/week05/数据类型04.py
{1, 2, 3, 4, 5, 6, 7}
[1, 2, 3, 4, 5, 6, 7]

Process finished with exit code 0

4.8.14 集合转变为不可变类型

【示例】:

set = {'alex', 'wusir', 'leon', 'shadow', 'dashi'}
fset = frozenset(set)
print(fset, type(fset))
for i in fset:
    print(i)

【结果】:

D:\WorkSpace\Python\venv\Scripts\python.exe D:/WorkSpace/Python/python_study/week05/数据类型04.py
frozenset({'alex', 'dashi', 'wusir', 'shadow', 'leon'}) <class 'frozenset'>
alex
dashi
wusir
shadow
leon

Process finished with exit code 0

4.9 数据类型转换

4.9.1 int转str

i = 1
s = str(i)

4.9.2 init转bool

i = 3           # 只要是0 就是False  非0就是True
b = bool(i)

4.9.3 str转int

s = '123'       # 字符串中只能是数字,不能含其他字符,否则报错
i = int(s)

4.9.4 str转bool

s = ""          # 空字符串为False
s = "0"         # 非空字符串都是True
if s

4.9.5 str转list

s.split(',')    # 以,分割字符串为列表

4.9.6 list转str

s = ''.join(li)

4.9.7 list转set

set = set(li)

4.9.8 set转list

li = list(set)

第5章 基本运算符

运算按种类可分为算数运算、比较运算、逻辑运算、赋值运算、成员运算、身份运算、位运算

5.1 算数运算符

以下假设变量:a=10,b=20

图片[1]|Python基础-python语言基础|leon的博客

5.2 比较运算符

以下假设变量:a=10,b=20

图片[2]|Python基础-python语言基础|leon的博客

5.3 赋值运算符

图片[3]|Python基础-python语言基础|leon的博客

5.4 逻辑运算符

在没有()的情况下not 优先级高于 and,and优先级高于or,即优先级关系为( )>not>and>or,同一优先级从左往右计算。

图片[4]|Python基础-python语言基础|leon的博客

5.5 in,not in

判断子元素是否在原字符串(字典,列表,集合)中

print('喜欢' in 'dkfljadklf喜欢hfjdkas')   # True
print('a' in 'bcvd')                        # False
print('y' not in 'ofkjdslaf')               # True

第6章 深浅拷贝

6.1 浅拷贝

【说明】:

浅拷贝只针对第一层(list/set等数据类型)进行拷贝,第一层改变时不影响源变量的第一层,其他层变化时则源变量同时做改变。

【示例】:

husband = ["zhangfu", 123, [15000, 9000]]
print(husband)
wife = husband.copy()
wife[0] = "laopo"
wife[1] = 456
print(wife)
print(husband)

【结果】:

D:\WorkSpace\Python\venv\Scripts\python.exe D:/WorkSpace/Python/python_study/week05/深浅copy.py
['zhangfu', 123, [15000, 9000]]
['laopo', 456, [15000, 9000]]
['zhangfu', 123, [15000, 9000]]

Process finished with exit code 0

6.2 深拷贝

【说明】:

深拷贝对变量进行完全拷贝,新的变量做任何改变都不影响源变量的数据。

【示例】:

husband = ["zhangfu", 123, [15000, 9000]]
wife = husband.copy()
wife[0] = "laopo"
wife[1] = 456
erzi = copy.deepcopy(husband)  # 深拷贝
erzi[0] = "saner"
erzi[1] = 666
print(xiaosan)

erzi[2][1] -= 1500
wife[2][1] -= 3000

print(husband)
print(wife)
print(erzi)

【结果】:

D:\WorkSpace\Python\venv\Scripts\python.exe D:/WorkSpace/Python/python_study/week05/深浅copy.py
['saner', 666, [15000, 9000]]
['zhangfu', 123, [15000, 6000]]
['laopo', 456, [15000, 6000]]
['saner', 666, [15000, 7500]]

Process finished with exit code 0
温馨提示:本文最后更新于2022-12-20 20:57:46,已超过483天没有更新。某些文章具有时效性,若文章内容或图片资源有错误或已失效,请联系站长。谢谢!
转载请注明本文链接:https://blog.leonshadow.cn/763482/1232.html
© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享