百度飞桨领航团零基础Python速成营第二天
【飞桨】、【百度领航团】、【零基础Python】
https://aistudio.baidu.com/aistudio/course/introduce/7073
字符串进阶
索引,切片
切片的语法:[起始:结束:步长] 字符串[start: end: step] 这三个参数都有默认值,默认截取方向是从左往右的 start:默认值为0; end : 默认值未字符串结尾元素; step : 默认值为1;如果切片步长是负值,截取方向则是从右往左的。
字符串一些函数:
string = 'hello_world'
string.endswith('ld') # 返回布尔值
string.startswith('he') # 返回布尔值
string.count('o') #显示自定义字符在字符串中个数
string.find('o') #返回从左第一个指定字符的索引,找不到返回-1
string.index('o') #返回从左第一个指定字符的索引,找不到报错
'hello' in string #返回布尔值,在字符串中是否存在
string.split('_') #按照指定的内容进行分割
string.replace('_',' ') #从左到右替换指定的元素,可以指定替换的个数,默认全部替换
my_string = "I wish to wish the wish you wish to wish, but if you wish the wish the witch wishes, I won't wish the wish you wish to wish."
my_string.replace('wish','wish'.upper(), 3)
#字符串标准化
my_string = ' hello world\n'
my_string.strip()
#大小写
my_string = 'hello_world'
my_string.upper()#大写
my_string.lower()#小写
my_string.capitalize()#首字母大写
字符串的格式化输出
一种可读性更好的方法 f-string
name = 'Molly'
hight = 170.4
score_math = 95
score_english = 89
print(f"大家好!我叫{name},我的身高是{hight:.3f} cm, 数学成绩{score_math}分,英语成绩{score_english}分")
list进阶
list1 = ['a','b','c','d','e','f']
list1.append('g') # 在末尾添加元素
list1.insert(2, 'ooo') # 在指定位置添加元素,如果指定的下标不存在,那么就是在末尾添加
list2 = ['z','y','x']
list1.extend(list2) #合并两个list list2中仍有元素
list1.count('a')#返回a的数量
list1.index('a')#返回第一个a的索引
'a' in list1#返回布尔值
list1.pop(3)#取出倒数第三个元素,并在原list中删除
list1.remove('a')#删除第一个自定义字符
列表每一项的操作
# 有点土但是有效的方法
list_1 = [1,2,3,4,5]
for i in range(len(list_1)):
list_1[i] += 1
list_1
# pythonic的方法 完全等效但是非常简洁
[n+1 for n in list_1]
#引申
# 1-10之间所有数的平方
[(n+1)**2 for n in range(10)]
# 1-10之间所有数的平方 构成的字符串列表
[str((n+1)**2) for n in range(10)]
# 小练习:0-29之间的奇数
list_1 = range(30)
[n for n in list_1 if n%2!=0]
#总结
[对n做的操作 for n in 目标list n的判断条件]
# 取两个list的交集
list_A = [1,3,6,7,32,65,12]
list_B = [2,6,3,5,12]
[i for i in list_A if i in list_B]
#小练习 在list_A 但是不在list_B中
list_A = [1,3,6,7,32,65,12]
list_B = [2,6,3,5,12]
[i for i in list_A if i not in list_B]
#双层for循环
[m + n for m in 'ABC' for n in 'XYZ']
生成器
L = [x * x for x in range(10)] #列表
g = (x * x for x in range(10)) #生成器
#可用next()每一个访问
next(g)
#也可用for循环输出
for n in g:
print(n)
# 练习 斐波那契数列
def feb(max_num):
n_1 = 1
n_2 = 1
n = 0
while n<max_num:
if n == 0 or n == 1:
yield 1
n += 1
else:
yield n_1 + n_2
new_n_2 = n_1
n_1 = n_1 + n_2
n_2 = new_n_2
n += 1
#yield可以理解为return,但是return后会继续执行
总结
第二天内容基本如上。