python基础速通

python基础速通

python没有什么框架,直接写。

1. 常用基础

1.1 注释:

# 单行注释

"""
第一行注释
第二行注释
第三行注释
"""

'''
注释1
注释2
注释3
'''

1.2 输入

默认都是字符串!输入数字也是字符串

password = input('请输入您的密码:')
print(f'您输入的密码是{password}')
print(type(password))

1.3 格式化输出:

基本数据类型

age = 18
name = 'TOM'
weight = 75.5
stu_id = 1
stu_id2 = 1000
# 0.不用判断数据类型,对应位置输出,最实用:
print(f'我的名字是{name},今年{age}岁了')
# 0.只要值,无脑%s
print('我的名字是%s,今年%s岁了,体重%s公斤' % (name, age, weight))
# print输出都是 自动换行 的!!

#需判断数据类型,叫较麻烦
# 1. 今年我的年龄是x岁 -- 整数 %d
print('今年我的年龄是%d岁' % age)
# 2. 我的名字是x -- 字符串 %s
print('我的名字是%s' % name)
# 3. 我的体重是x公斤 -- 浮点数 %f
print('我的体重是%.3f公斤' % weight)
# 4. 我的学号是x -- %d
print('我的学号是%d' % stu_id)
# 4.1 我的学号是001
print('我的学号是%03d' % stu_id)
print('我的学号是%03d' % stu_id2)
# 5. 我的名字是x,今年x岁了
print('我的名字是%s,今年%d岁了' % (name, age))
# 5.1 我的名字是x,明年x岁了
print('我的名字是%s,明年%d岁了' % (name, age + 1))
# 6. 我的名字是x,今年x岁了,体重x公斤,学号是x
print('我的名字是%s,今年%d岁了,体重%.2f公斤,学号是%06d' % (name, age, weight, stu_id))

高级数据类型

dict1 = {'name': 'TOM', 'age': 20, 'gender': '男'}
print(dict1) # {'name': 'TOM', 'age': 20, 'gender': '男'}
print(f"复合列表{dict1}啦啦啦") # 复合列表{'name': 'TOM', 'age': 20, 'gender': '男'}啦啦啦

1.4 数据类型

自动检测数据类型,走不通时就报错!javascript 也是

num1 = 1 # int -- 整型
num2 = 1.1 # float -- 浮点型,就是小数
b = True  # bool -- 布尔型,通常判断使用,布尔型有两个取值 True 和 False
my_name = 'TOM'  # str -- 字符串,特点:数据都要带引号
c = [10, 20, 30] # list -- 列表
d = (10, 20, 30) # tuple -- 元组
e = {10, 20, 30} # set -- 集合
f = {'name': 'TOM', 'age': 18} # dict -- 字典 -- 键值对

#强制类型转换 
int() bool() str()
tuple(list1) list(tuple1)

#eval() 识别字符串值的数据类型!返回一个对象
str2 = '1'
str3 = '1.1'
str4 = '(1000, 2000, 3000)'
str5 = '[1000, 2000, 3000]'
print(type(eval(str4)))  # <class 'tuple'>

1.5 各种符

1.5.1 转义字符
print('hello\nPython')  # \n 换行
print('\tabcd') # \t 空格
1.5.2 结束符
print('hello', end="\n") # 换行
print('world', end="\t") # 空格
print('hello', end="...") # 以...结束
print('Python')
1.5.3 运算符

同c

a = 10
a += 1  # a = a + 1
print(a)
b = 10
b -= 1  # b = b - 1
print(b)
# 先算复合赋值运算符右面的表达式
c = 10
c += 1 + 2
print(c)
d = 10
d *= 1 + 2
print(d)
1.5.4 逻辑运算符
a = 0
b = 1
c = 2
# 1. and: 与: 都真才真
print((a < b) and (c > b))
print(a > b and c > b)
# 2. or:或 : 一真则真,都假才假
print(a < b or c > b)
print(a > b or c > b)
# 3. not: 非: 取反
print(not False)
print(not c > b)
1.5.5 三目运算符
a = 1
b = 2
c = a if a > b else b #取最大,很独特嘛

1.6 随机数

import random
num = random.randint(0, 2)

2. 控制语句

2.1 判断

age = int(input('请输入您的年龄:'))
if age >= 18:
    print(f'您输入的年龄是{age}, 已经成年,可以上网')

if age >= 18:
	print(f'您输入的年龄是{age}, 已经成年,可以上网')
else:
	print(f'您输入的年龄是{age},小朋友,回家写作业去')  
    
if age < 18:
    print(f'您输入的年龄是{age}, 童工')
#elif (age >= 18) and (age <= 60):
elif 18 <= age <= 60:
    print(f'您输入的年龄是{age}, 合法')
elif age > 60:
    print(f'您输入的年龄是{age}, 退休年龄')
else:
    # ...

2.2 循环 for

while没啥区别,这个for跟c天差地别!

基础用法
# break:当某些条件成立,退出整个循环
# continue,直接下次一定,在continue之前一定要修改计数器,否则进入死循环
i = 1
while i <= 5:
    print('媳妇儿,我错了')
    i += 1

while i <= 5:
    print('媳妇儿,我错了')
    i += 1
else: # 循环结束,必定执行,没有也没区别嘛!
    print('媳妇原谅我了,真开心呐,哈哈哈哈')

# for in
str1 = 'itheima'
for i in str1: # for 自动迭代!int本身没有迭代
    print(i) # 竟然自动换行!输出每一个字符

for i in str1:
    print(i)
else:
    print('循环正常结束执行的else的代码')

小试牛刀

for i in rangefor i in enumerate

# for range(start, end, step)
# 1. 如果不写开始strat,默认从0开始
# 2. 如果不写步长step,默认为1
for i in range(1, 10, 2):
    print(i,end=' ')  # 1 3 5 7 9
for i in range(1, 10):
    print(i) # 1 2 3 4 5 6 7 8 9
for i in range(10):
    print(i) # 0 1 2 3 4 5 6 7 8 9
    
# enumerate
list1 = ['a', 'b', 'c', 'd', 'e']
print(enumerate(list1)) # 可迭代对象<enumerate object at 0x000001BA70647180>
# 只能用for迭代?
for i in enumerate(list1):
    print(i) # (0, 'a') (1, 'b') (2, 'c') (3, 'd') (4, 'e') 元组(下标,数据)
for i in enumerate(list1, start=2):
    print(i) # (2, 'a') (3, 'b') (4, 'c') (5, 'd') (6, 'e')
大显身手

推导式:列表,元组,集合,字典,

# 列表推导式
list1 = [i for i in range(10)] # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
list2 = [i for i in range(0, 10, 2)] # [0, 2, 4, 6, 8]
list3 = [i for i in range(10) if i % 2 == 0] # [0, 2, 4, 6, 8]
list4 = [(i, j) for i in range(1, 3) for j in range(3)] # 1,2  0,1,2
# [(1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)]

# 字典推导式
dict1 = {i: i**2 for i in range(1, 5)} # {1: 1, 2: 4, 3: 9, 4: 16}
    # 列表合并为字典
list1 = ['name', 'age', 'gender', 'id']
list2 = ['Tom', 20, 'man']
dict1 = {list1[i]: list2[i] for i in range(len(list2))} # {'name': 'Tom', 'age': 20, 'gender': 'man'}
	# 按要求取子字典
counts = {'MBP': 268, 'HP': 125, 'DELL': 201, 'Lenovo': 199, 'acer': 99}
dict1 = {key: value for key, value in counts.items() if value >= 200}
print(dict1) # {'MBP': 268, 'DELL': 201},取除value >= 200 的,合并为子字典。

# 集合推导式
list1 = [1, 1, 2]
set1 = {i ** 2 for i in list1} # {1, 4} 自动去重

3. 数据容器

3.1 字符串

定义、初始化
b = "TOM"
e = '''i am TOM'''
 # 里面有单引号
c = "I'm TOM"  
d = 'I\'m TOM' #转义
# 打印输出没有换行,空格分开!
a = 'hello ' \
    'world'
# 打印输出也会换行:
f = """I  
am TOM"""
输入,输出、遍历

默认输入都是字符串!输入数字也是字符串

password = input('请输入您的密码:')
print("hello world") # 直接打印
name = 'ROSE'
print('我的名字是%s' % name)
print(f'我的名字是{name}')

# 遍历
# 输出 下标,字符 ,自动换行
n=0
for i in name:
    print(n,i)
    n+=1
切片,下标

左闭右开: [ )

# 序列名[开始位置的下标:结束位置的下标:步长]
str1 = '012345678'
print(str1) # 012345678
print(str1[0]) # 0
print(str1[2:5])  # 234
print(str1[2:5:2])  # 24
print(str1[2:5])  # 234
print(str1[:5])  # 01234 -- 如果不写开始,默认从0开始选取
print(str1[2:])  # 2345678 -- 如果不写结束,表示选取到最后
print(str1[:])  # 012345678 -- 如果不写开始和结束,表示选取所有

# 负数测试
print(str1[::-1])  # 876543210 -- 如果步长为负数,表示倒叙选取
print(str1[-4:-1])  # 567 -- 下标-1表示最后一个数据,依次向前类推

# 终极测试
print(str1[-4:-1:1])  # 567
print(str1[-4:-1:-1])  # 不能选取出数据:从-4开始到-1结束,选取方向为从左到右,但是-1步长:从右向左选取
# **** 如果选取方向(下标开始到结束的方向) 和 步长的方向冲突,则无法选取数据
print(str1[-1:-4:-1])  # 876
常用方法
查找下标

字符、子串:.find() .rfind() .index() .rindex() .count()

# find() 正向,找到就返回!
mystr = "hello world and itcast and itheima and Python"
str2='D:\\A01.学习资料\\001学习资料\\大二上\\大学物理下\\作业提交\\第8周\\test2\\15.26.jpg' # 转义 转义 => \这个符号
print(mystr.find('and'))  # 12
print(mystr.find('and', 15, 30))  # 23
print(mystr.find('ands'))  # -1 , ands子串不存在,打印-1
# rfind() 反向,从后往前找,找到直接返回下标!
print( str2.rfind('\\') ) # 44
# index() 查找,只有一点不同find
print(mystr.index('and'))  # 12
print(mystr.index('and', 15, 30))  # 23
# print(mystr.index('ands'))  # 如果index查找子串不存在,报错
# rindex() 反向同理
print(mystr.rindex('and')) # -1
print(mystr.rindex('ands')) # 3
# count() 数量
print(mystr.count('and', 15, 30)) # 1
print(mystr.count('and'))  # 3
print(mystr.count('ands'))  # 0
替换修改

replace() split() join()

mystr = "hello world and   itcast   and itheima and Python"
# 1. replace() 把and换成he ,返回修改后的字符串
new_str = mystr.replace('and', 'he')
new_str = mystr.replace('and', 'he', 1) # 只换第一个
# 替换次数如果超出子串出现的次数,表示替换所有这个子串
new_str = mystr.replace('and', 'he', 10)
# 原有字符串的数据并没有做到修改 字符串是不可变数据类型

# 2. split() -- 分割,返回一个列表, 丢失分割字符
list1 = mystr.split('and') # 
list1 = mystr.split() # 按空格分!无论空格多少 
# ['hello', 'world', 'and', 'itcast', 'and', 'itheima', 'and', 'Python']
# 只分割前两个
list1 = mystr.split('and', 2) # ['hello world ', ' itcast ', ' itheima and Python']

# 3. join() -- 合并列表里面的字符串数据为一个大字符串
mylist = ['aa', 'bb', 'cc']
new_str = '...'.join(mylist) # aa...bb...cc
new_str = ''.join(mylist) # aabbcc

# 1. capitalize() 字符串首字母大写
new_str = mystr.capitalize()
# 2.title(): 字符串中每个单词首字母大写
new_str = mystr.title()
# 3. upper():小写转大写
new_str = mystr.upper()
# 4. lower(): 大写转小写
new_str = mystr.lower()

# 原字符串都不会变!!!
# 1. lstrip(): 删除左侧空白字符 "   aaaaa     "
new_str = mystr.lstrip() # aaaaa     
# 2. rstrip(): 删除右侧空白字符 
new_str = mystr.rstrip() #    aaaaa
# 3.strip():删除两侧空白字符,无论多少
new_str = mystr.strip() # aaaaa
print(new_str)
判断值类型
mystr = "hello world and itcast and itheima and Python"
# 1. startswith(): 判断字符串是否以某个子串开头
print(mystr.startswith('hello')) # true
print(mystr.startswith('hel')) # true
print(mystr.startswith('hels')) # false
# 2. endswith(): 判断字符串是否以某个子串结尾
print(mystr.endswith('Python')) # true
print(mystr.endswith('Pythons')) # false
# 3. isalpha(): 是否是字母
print(mystr.isalpha()) # false
# 4. isdigit(): 数字
print(mystr.isdigit()) # false
mystr1 = '12345'
print(mystr1.isdigit()) # true
# 5. isalnum() : 数字或字母或组合
print(mystr1.isalnum()) # true
print(mystr.isalnum()) # false
mystr2 = 'abc123'
print(mystr2.isalnum()) # true
# 6.isspace(): 空白
print(mystr.isspace()) # false
mystr3 = '   '
print(mystr3.isspace()) # true

3.2 元组 ( ) tuple

不可修改

定义:
# 1. 多个数据元组
t1 = (10, 20, 30)
print(type(t1)) # tuple
# 2. 单个数据的元组,也要加逗号
t2 = (10,)
print(type(t2))

# 3. 如果单个数据的元组不加逗号
t3 = (10)
print(type(t3))  # int

t4 = ('aaa')
print(type(t4))  # str
t5 = ('aaa',)
print(type(t5)) # tuple
常见操作:
t1 = ('aa', 'bb', 'cc', 'bb')
# 1. 下标
print(t1[0]) # aa
# 2. index()
print(t1.index('bb')) # 1
# print(t1.index('bbb')) # 没有会报错
# 3. count()
print(t1.count('aa')) # 1
print(t1.count('aaa')) # 0
# 4. len()
print(len(t1)) # 4

修改:一旦定义了,就不能修改!

t1 = ('aa', 'bb', 'cc', 'bb')
# t1[0] = 'aaa' # 报错,元组元素不能改!
t2 = ('aa', 'bb', ['cc', 'dd'])
t2[2][0] = 'TOM' # 但这样可以修改!!!本质还是修改列表
print(t2) # ('aa', 'bb', ['TOM', 'dd'])

遍历
t1 = ('aa', 'bb', 'cc', 'bb')
# 1. 直接打印遍历
print(t1) # ('aa', 'bb', 'cc', 'bb')
# 2. 万能的 in
for item in tuple1:
    print(item,end=' ') # 'aa', 'bb', 'cc', 'bb'

3.3 列表 [ ] list

列表数据类型竟然可以不一致

判存,数量
name_list = ['TOM', 'Lily', 'ROSE']
print(name_list) # 直接就遍历输出了 ['TOM', 'Lily', 'ROSE']
print(name_list[1]) # Lily
# 1. index()
print(name_list.index('TOM')) # 0
# print(name_list.index('TOMS')) # 没有会报错
# 2. count()
print(name_list.count('TOM')) # 1
print(name_list.count('TOMS')) # 0
# 3.len() 个数
print(len(name_list)) # 3
# 4. in
print('TOM' in name_list) # true
print('TOMS' in name_list) # false
# 5. not in
print('TOM' not in name_list) # false
print('TOMs' not in name_list) # true
增加,插入
name_list = ['TOM', 'Lily', 'ROSE']
# 1. append()
name_list.append('xiaoming') # ['TOM', 'Lily', 'ROSE', 'xiaoming']
name_list.append([11, 22]) #['TOM', 'Lily', 'ROSE', 'xiaoming', [11, 22]]
# 2. extend() 追加数据是一个序列,把序列拆开然后逐一追加到列表的结尾
name_list = ['TOM', 'Lily', 'ROSE']
name_list.extend('abc') # ['TOM', 'Lily', 'ROSE', 'a', 'b', 'c']
name_list.extend(['xiaoming', 'xiaohong']) # ['TOM', 'Lily', 'ROSE', 'a', 'b', 'c', 'xiaoming', 'xiaohong']
# 3. insert(下标,数据)
name_list = ['TOM', 'Lily', 'ROSE']
name_list.insert(1, 'aaa') # ['TOM', 'aaa', 'Lily', 'ROSE']
删除,清空
name_list = ['TOM', 'Lily', 'ROSE']
# 1. del
del name_list # 直接删除变量,不能用了
del(name_list) # 同上
del name_list[0] # 删除指定下标的数据 ['Lily', 'ROSE']
# 2. pop()
del_name = name_list.pop() # 默认删除最后一个数据,返回被删除的数据  ROSE
del_name = name_list.pop(1) # 删除指定下标的数据,返回被删除的数据 Lily
# 3. remove()
name_list.remove('ROSE')  # ['TOM', 'Lily']
# 4. clear() -- 清空
name_list.clear() # [],空列表,还能用
修改,复制
# 1. [] 修改指定下标的数据
name_list = ['TOM', 'Lily', 'ROSE']
name_list[0] = 'aaa'  # ['aaa', 'Lily', 'ROSE']
# 2. reverse() 逆序
list1 = [1, 3, 2, 5, 4, 6]
list1.reverse() # [6, 4, 5, 2, 3, 1]
# 3. sort() 排序:升序(默认) 和 降序
list1.sort() # 升,[1, 2, 3, 4, 5, 6]
list1.sort(reverse=False) # 升,[1, 2, 3, 4, 5, 6]
list1.sort(reverse=True) # 降,[6, 5, 4, 3, 2, 1]
# 4. copy() 复制
name_list = ['TOM', 'Lily', 'ROSE']
list1 = name_list.copy() # ['TOM', 'Lily', 'ROSE']
遍历
name_list = ['TOM', 'Lily', 'ROSE']
# 1. 直接打印
print(name_list) # ['TOM', 'Lily', 'ROSE']
# 2. 遍历处理
i = 0
while i < len(name_list):
    print(name_list[i])
    i += 1
for item in name_list:
    print(item)
#嵌套,二维
name_list = [['TOM', 'Lily', 'Rose'], ['张三', '李四', '王五']]
name_list[0][1] # Lily 下标遍历,较麻烦
for item1 in name_list: # 直接for!
    for item2 in item1:
        print(item2,end = " ") # TOM Lily Rose 张三 李四 王五

3.4 字典 { } dict

键值对

基操

定义,删除,修改,查找

# 1.定义,竟然可以任意键值对
dict1 = {1: 2, 'a': 3}
dict2 = {} # 空字典
dict1['a'] = 'b' # 有则改 {1: 2, 'a': 'b'} 
# 无则增 {1: 2, 'a': 'b', 'id': 110}
dict1['id'] = 110 

dict1 = {'name': 'TOM', 'age': 20, 'gender': '男'}
# 2.删除、清空
del(dict1) # 删除字典
del dict1['name'] # 根据key 删指定的键值对
# del dict1['names']  # 没有会报错!
dict1.clear() # 清空 {}

dict1 = {'name': 'TOM', 'age': 20, 'gender': '男'}
# 3.查找
print(dict1['names']) # 没有会报错!
# get()
dict1.get('name') # TOM,返回 key name的 value
dict1.get('names')  # 没有不会报错!返回None
dict1.get('names', 'Lily') # Lily。没有就返回 'Lily' (str类型)
dict1.get('name', 'Lily') # TOM 有就返回值,没有返回指定的。
if dict1.get('aaa'):
    #有
else:
    #无
遍历
dict1 = {'name': 'TOM', 'age': 20, 'gender': '男'}
# 1. 直接打印遍历,会带中括号
print(dict1) # {'name': 'TOM', 'age': 20, 'gender': '男'}
print(dict1.keys()) # dict_keys(['name', 'age', 'gender']),可是可迭代对象
print(dict1.values()) # dict_values(['TOM', 20, '男'])
print(dict1.items()) # dict_items([('name', 'TOM'), ('age', 20), ('gender', '男')])

# 2. 常用:直接for in 默认遍历key
for key in dict1:
    print(key,kwargs[key]) # name TOM  age 20  gender 男
    
# 3大方法: .keys() .values() .items():
for key in dict1.keys(): # name:TOM, age:20, gender:男, 
    print(key, end=":")
    print(dict1[key], end=", ")
for value in dict1.values(): # TOM 20 男
    print(value,end=" ")
for item in dict1.items(): # ('name', 'TOM') ('age', 20) ('gender', '男') 
    print(item,end=" ")  # item 为元组!!!
    
# 拆包,本质为元组的拆包
for key, value in dict1.items():
    print(f'{key}={value}',end=" ") # name=TOM age=20 gender=男 

3.5 集合 { } set

自动去重,类型也可以不一致,增删改查。

# 1. 集合,自动去重!顺序会不一致
s1 = {10, 20, 30, 40, 50}
# print(s1[0]) 报错! 不能下标访问
print(s1)  # {40, 10, 50, 20, 30}
s2 = {10, 30, 20, 40, 30, 20}
print(s2) # {40, 10, 20, 30}
s3 = set('abcdefg') # 自动拆字符串
print(s3) # {'g', 'b', 'c', 'e', 'd', 'f', 'a'}

# 2. 创建空集合: set()
s4 = set()
s5 = {} # 这是字典!!

# 3. 增加
s1 = {10, 20}
s1.add(100) # {100, 10, 20},只能一个一个加
s1.add(100) # 去重,已有数据什么事情都不做
s1.update([20, 30, 40]) # 通过列表,批量添加 {100, 40, 10, 20, 30}

# 4. 删除
s1 = {10, '20', 30, 40, 50} 
s1.remove(10) # remove(): 删除指定数据,如果数据不存在 报错
s1.discard(10) # discard():删除指定数据,如果数据不存在 不报错
s1.pop() # pop(): 随机删除某个数据,并返回这个数据

# 5. 查找 in 或not in 判断数据10是否存在
if 10 in s1: # True
    # 
if 10 not in s1: # False
    #

3.6 类型转换

tuple() # 转换成元组
list() # 转换成列表d
set() # 转换成集合,同时去重
list1 = [10, 20, 30, 20, 40, 50] # 列表
s1 = {100, 300, 200, 500} # 集合
t1 = ('a', 'b', 'c', 'd', 'e','a') # 元组
print(set(list1))  # {40, 10, 50, 20, 30}
print(set(t1)) # {'a', 'd', 'c', 'e', 'b'}

4. 公共操作

4.1 加号 +

字符串,列表,元组

s = 'aa' + 'bb' # 字符串
list1 = [1,4] + [2,3] # 列表
tuple1 = (1,4) + (2,3) # 元组
# 字典dict不行,集合set也不行

4.2 乘号 *

字符/串,列表,元组

'a' * 5 # 复制 'aaaaa'
['hello'] * 5 # ['hello', 'hello', 'hello', 'hello', 'hello']
('world',) * 5 # ('world', 'world', 'world', 'world', 'world')

4.3 判存 (not) in

都行:字符串、列表、元组、字典、集合

# 前3个很好理解,略
# 字典首秀:
dict1 = {'name': 'Python', 'age': 30}
if 'python' in dict1: # false
if 'name' in dict1: # true,这俩都是判key!
if 'name' in dict1.keys(): # true
if 'name' in dict1.values(): # 判值value
if 'name' not in dict1: # false
    
# 集合首秀
s1 = {10, '20', 30, 40, 50} 
if 10 in s1: # True
if 10 not in s1: # False

4.4 长度 len

都行:字符串、列表、元组、字典、集合

str1 = 'abcdefg'
print(len(str1)) # 7
list1 = [10, 20, 30, 40, 50]
print(len(list1)) # 5
t1 = (10, 20, 30, 40, 50)
print(len(t1)) # 5
s1 = {10, 20, 30, 40, 50}
print(len(s1)) # 5
dict1 = {'name': 'TOM', 'age': 18}
print(len(dict1)) # 2

4.5 删除 del

通过下标删成员del xxx[0]:只有列表、字典可以!字符串、元组、集合都不行

# 1. del 变量:直接删除变量,都可以删。略。
# 2. del 成员:
str1 = 'abcdefg'
# del str1[2] 字符串不行!!
list1 = [10, 20, 30, 40, 50]
del list1[0] # 列表可以
print(list1) # [20, 30, 40, 50]
t1 = (10, 20, 30, 40, 50)
# del t1[0] 元组不行
s1 = {10, 20, 30, 40, 50}
# del s1[0] 集合也不行,自动去重乱序,不能下标访问
dict1 = {'name': 'TOM', 'age': 18}
del dict1['name'] # 有key才可以,没有会报错
print(dict1) # {'age': 18}

4.6 最值 max( ) min( )

都行:字符串、列表、元组、字典、集合

str1 = 'abcdefg'
list1 = [10, 20, 30, 40, 50]
t1 = (10, 20, 30, 40, 50)
s1 = {10, 20, 30, 40, 50}
dict1 = {'name': 'TOM', 'age': 18}
print(max(str1)) # g
print(max(list1)) # 50 
print(max(t1)) # 50
print(max(s1)) # 50 
print(max(dict1)) # name,相当于max(dict1.keys())

4.7 拆包

接受变量个数必须与里面元素个数相同,适用于数据较少时

# 1. 字符串、元组,列表,集合同理
a = (1,2) # a就是整个元组!
a,b = (1,2) # a为1,b为2
# a,b = (1,2,3) 多一个,少一个都不行

a,b = [1,2]

a,b = "12" # a 为 '1',b 为 '2'

a,b = {1,2}

# 2. 字典
dict1 = {'name': 'TOM', 'age': 20}
a, b = dict1 # 默认都为key
print(a,dict1[a])  # name TOM
print(b,dict1[b]) # age 20

# 3. 大开眼界:
a, b = 1, 'str'
print(a,b) # 1 'str'
a, b = b, a # 直接交换两个变量的值,不同类型也可以!
print(a,b) # 'str' 1

4.8 引用

可变数据类型:列表、字典、集合(心连心)

不可变数据类型:int …数字型、字符串(赋值另存)、元祖(不可更改)

# 1. 对可变数据类型:列表、字典、集合,a变则b变,b变a也变
# 列表
a = [10, 20]
b = a 
# 集合
a = {10, 20}
b = a 
# 字典
a = {10:'a', 20:2}
b = a # 
b[30] = 'c' # a,b都为{10: 'a', 20: 2, 30: 'c'}

# 2. 不可变数据类型
a = 1
b = a # 一开始的id仍然相同,变化时才单纯的复制!无关联。

5. 函数

5.1 定义

def sel_func(): # 无参,无返
    print('显示余额')
def add_num2(a, b): # 有参,无返
    result = a + b
def buy(): # 无参,有反
    return '烟'
def sum_num(a, b): # 有参,有反
    return a + b
def return_num(): # (100, 200),多个返回值为元组
    return 100, 200  
def user_info(*args): # args为元组,一个*号,所有参数封装为元组
    # ...
def user_info(**kwargs): # kwargs为字典,2个*号,所有参数封装为字典
    # ...
# 说明文档
def sum_num1(a, b):
    """
    求和函数sum_num1
    :param a: 参数1
    :param b: 参数2
    :return: 返回值
    """
    return a + b
help(sum_num1) # 查看函数说明文档

5.2 global关键字

函数体类为局部变量,可以访问全部变量,但不能直接改变全局变量

a = 100
def testA():
    a = 200
    print(a)
testA() # 200,不能改变全局的a
print(a) # 100

a = 100
def testA():
    global a # 多这一行
    a = 200
    print(a)
testA()# 200
print(a) # 200 全局的a也改了!!

5.3 传参

def user_info(name, age, gender):
    print(f'您的姓名是{name}, 年龄是{age}, 性别是{gender}')
# 1. 按定义的顺序
user_info('ROSE', 20, '女')
# 2. 关键字传参,必须写在位置参数的后面。
user_info('小明', gender='男', age=18) # 参数键不分顺序

# 3. 默认值
def user_info(name, age, gender='男'):
    print(f'您的姓名是{name}, 年龄是{age}, 性别是{gender}')
    
# 4. 不定长参数
# 4.1 元组tuple()
def user_info(*args):
    print(args)
    for item in args:
        print(item)
user_info() # ()
user_info('TOM') # ('TOM',)    TOM
user_info('TOM', 20) # ('TOM', 20)    TOM 20

# 4.2 字典dict{key:value}
def user_info(**kwargs):
    print(kwargs)
    for item in kwargs:
        print(item,kwargs[item])
user_info() # {}
user_info(name='TOM') # {'name': 'TOM'}      name TOM
user_info(name='TOM', age=20) # {'name': 'TOM', 'age': 20}   name TOM age 20

5.4 lambda匿名函数

就用一次!

# lambda:参数:返回值
lambda: 100 # 无参
lambda a, b: a + b # 有参
lambda a, b, c=100: a + b + c # 有参,默认值
lambda *args: args # 可变参,元组
lambda **kwargs: kwargs # 可变参,字典
lambda a, b: a if a > b else b

# 好高深的用法呀!也挺有用
students = [
    {'name': 'TOM', 'age': 20},
    {'name': 'ROSE', 'age': 19},
    {'name': 'Jack', 'age': 22}
]
# .sort(key = func1) key接受函数名,列表每个值经这个函数处理后,按照对应的返回值排序列表中的元素!
students.sort(key = lambda x: x['name']) # 根据 'name'的值排序!默认升序
# [{'name': 'Jack', 'age': 22}, {'name': 'ROSE', 'age': 19}, {'name': 'TOM', 'age': 20}]
students.sort(key=lambda x: x['age']) # 同理,按age排序。

5.5 函数作参数

def sum_num(a, b, f): # f为函数名
    return f(a) + f(b) # 使用函数参数!!
def func1(a):
    return a+1
print(sum_num(-1, 5, func1)) # -1+1 + 5+1 = 6

5.6 内置函数

内置函数,直接用就是。68 个 Python 内置函数介绍

abs() # 绝对值
round() # 四舍五入

6. 文件

无非就读、写操作!

二进制读写:就是一般的模式后面添个b!

f = open('test.txt', 'w+b')
f = open('test.txt', 'rb')
f = open('test.txt', 'a+b')

6.1 写文件

# 'w' :创建 / 覆盖 test.txt,写入字符串
f = open('test.txt', 'w') # 先清空!好不讲理!
f.write('aaa') # 1. write()
f.close()
# 'a' : 创建 / 追加字符串
f = open('test2.txt', 'a') # 2. writelines()
f.writelines(['xyz','abc\n','ssss']) # 批量写入,不会自动换行
f.close()

6.2 读文件

# 1. read() 读取后,f在末尾字符的后一个位置!!
f = open('test.txt') # 不写,默认只读,等效f = open('test.txt','r') 
print(f.read()) # 读取所有。
f.seek(0) # 文件指针归零。从f处开始读
print(f.read(10)) # 读取10个字符,换行也算一个!读取后f在第11个字符处
f.close()

# 2. readlines() 
f = open('test.txt', 'r')
con = f.readlines()
print(con) # ['aaaaa\n', 'bbbbb\n', 'ccccc\n', 'ddddd\n', 'eeeee']
f.close()

# 3. readline() 读取后,f在下一行开始!
f = open('test.txt', 'r')
con = f.readline()
print(con) # aaaaa 字符串\n换行了!
con = f.readline()
print(con) # bbbbb f指针会移到下一行开始

6.3 同时读写

都可读可写,但还是有一点区别:

f = open('test.txt', 'a+') # 打开后指针f在末尾,无文件则创建文件
  f = open('test.txt', 'w+') # 慎用,先清空文件!打开后指针f在开头,无则创建文件
f = open('test.txt', 'r+') # 打开后指针f在开头,无则报错!
# 以二进制形式读写:不会

6.4 文件指针

#改变指针位置 .seek(偏移量, 起始位置)  起始位置:0开头 1当前 2 结尾字符还要后一个的位置,默认开头
f.seek(0) # 移动到开头(第1个字符),起始位置默认为开头!
f.seek(0, 0) # 同上
f.seek(2) # 移动到第3个字符处!
f.seek(2,0) # 同上

# 以二进制形式打开'a+b'、'r+b',第2个参数才可以为1或者2
f.seek(2, 1) # 当前,右移2格。
f.seek(-2, 2) # 倒数第2个字符处

6.5 文件夹操作

使用os模块!

import os

# 1. rename(): 重命名
os.rename('1.txt', '10.txt') # 没有1.txt会报错!
# 8. rename() -- 重命名文件夹 bb重命名为bbbb
os.rename('bb', 'bbbb') # 没有bb文件见会报错。但bb里有文件(夹),不会报错!

# 2. remove(): 删除文件
os.remove('10.txt') # 没有也会报错!

# 3. mkdir():创建文件夹
os.mkdir('aa') # 文件夹已存在会报错!

# 4.rmdir(): 删除文件夹
os.rmdir('aa')  # 里面不是空的,会报错!

# 5. getcwd(): 返回当前文件所在目录路径
print(os.getcwd())  # 只到文件所在文件夹 D:\a01Study\...\D13_文件

# 6. chdir():改变目录路径
os.mkdir('aa')
os.chdir('aa') # 进入到aa文件夹
os.mkdir('bb') # 在aa里面,创建bb文件夹

# 7. listdir(): 获取当前文件夹下所有文件和文件夹,返回一个列表
print(os.listdir()) # ['2.txt', '2[备份].txt', 'aa', 'bbbb', 'hm.py']
print(os.listdir('aa')) # 当前文件夹中,aa文件夹中的文件目录

6.6 小项目

6.6.1 复制文件.pro
old_name = 'ffff.test1.txt'
dot_index = old_name.rfind('.')
postfix = old_name[index:] # 提取.后缀,没有后缀不行!左闭右开
new_name = old_name[:index] + '[复制]' + postfix
old_f = open(old_name, 'rb')
new_f = open(new_name, 'wb')
# 一个读,一个写
while True:
    con = old_f.read(1024) #每次指针会移动的!所以能不断读,直到读完。
    if len(con) == 0:
        # 表示读取完成了
        break
    new_f.write(con)
old_f.close()
new_f.close()
6.6.2 批量重命名

把code文件夹所有文件重命名 Python_xxxx

# 把code文件夹所有文件、文件夹,重命名 Python_xxxx
import os
# 标志:1,全部名称添加Python_  2,改之后,改回来,去掉Python_
flag = 1
# 1. 找到所有文件、文件夹
file_list = os.listdir()
print(file_list)
# 2. 构造名字
for i in file_list:
    if flag == 1:
        # new_name = 'Python_' + 原文件i
        new_name = 'Python_' + i
    elif flag == 2:
        # 删除前缀
        num = len('Python_')
        new_name = i[num:]
# 3. 重命名
    os.rename(i, new_name)
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值