28_作业
# 1. 使用列表生成式创建一个包含1到20的平方的列表nums
# - 获取nums中前3个元素
# - 获取nums中奇数下标上的所有元素
# - 在nums的下标为5的位置处添加一个88
nums = [i ** 2 for i in range(1, 21)]
print(nums)
print(nums[:3])
print(nums[1::2])
nums.insert(5, 88)
print(nums)
# 2. 使用列表生成式创建一个包含1到20之间所有偶数的平方的列表。
print([i**2 for i in range(1, 21) if i % 2 == 0])
# 3. 使用列表生成式创建一个包含1到10之间所有奇数的倒数的列表。
print([1/i for i in range(1, 21) if i % 2 == 1])
# 4. 使用列表生成式创建一个包含1到20之间所有能被3整除的数的平方的列表。
print([i**2 for i in range(1, 21) if i % 3 == 0])
# 5. 使用列表生成式创建一个包含10到100之间所有十位数为偶数的数的平方的列表。
print([i**2 for i in range(10, 101) if (i // 10 % 10) % 2 == 0])
# 6. 使用列表生成式创建一个包含1到20之间所有能被7整除的数的立方加上1的列表。
print([i**3 + 1 for i in range(1, 21) if i % 7 == 0])
# 7. 使用列表生成式创建一个包含1到20之间所有个位数和十位数相等的数的平方根的列表。
print([i**(1/2) for i in range(1, 21) if i // 10 % 10 == i % 10])
# 8. 使用列表生成式创建一个包含1到20之间所有能被3和5同时整除的数的平方的列表。
print([i**2 for i in range(1, 21) if i % 15 == 0])
# 9. 使用列表生成式创建一个包含1到20之间所有十位数比个位数大2的数的列表。
print([i for i in range(1, 21) if (i // 10 % 10) - (i % 10) == 2])
# 10. `scores = [19, 27, 38, 41, 56, 72, 28, 65] `
# - 获取最大值所在的位置
# - 获取所有的偶数和
scores = [19, 27, 38, 41, 56, 72, 28, 65]
max_value = max(scores)
print(max_value)
print([i for i in range(len(scores)) if scores[i] == max_value])
print(sum([ele for ele in scores if ele % 2 == 0]))
29_元祖
元组(tuple)
和列表是类似的
列表是可变的有序序列;元组是不可变的有序序列
什么时候使用元组? 数据元素确定 且不会再发生变化 就可以使用元组
31天的月份 1 3 5 7 8 10 12
元组的数据标记是(), 列表的是[]
提高运算符优先级的时候 也是使用()
注意: 一元组[元组中有1个数据]定义的时候 元素后面必须加上逗号, 否则会识别成提高表达式优先级 就不是元组类型的
nums = (11)
nums1 = (11,)
print(type(nums), type(nums1)) # <class 'int'> <class 'tuple'>
# 判断输入的月份是否有30天
month = int(input('请输入月份:'))
year = int(input('请输入年份:'))
if month == 4 or month == 6 or month == 9 or month == 11:
print(month, '有30天')
if month in (4, 6, 9, 11):
print(year, '年', month, '月有30天')
elif month in (1, 3, 5, 7, 8, 10, 12):
print(year, '年', month, '月有31天')
else:
if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):
print(year, '年', month, '月有29天')
else:
print(year, '年', month, '月有28天')
nums = (11, 23, 45, 67, 87, 29, 45)
print(nums[:3])
# nums[0] = 19 不支持元素被修改的
# TypeError: 'tuple' object does not support item assignment
print(nums[-1])
# 当给一个变量 赋值的时候使用逗号分隔开多个数据 这个多个数据进行打包的操作 打包成元组赋值给变量
values = 11, 23, 45, 61, 72, 38, 49
print(type(values)) # <class 'tuple'>
# 解包 把一个容器中多个数据赋值给多个变量
a, b = 11, 23
print(a, b)
for item in enumerate([12, 34, 56, 71]):
print(item) # (0, 12) 将位置和该位置的元素组合成元组 放在一个新的容器A中 这个A就是一个二维容器
30_字符串
字符串是容器型数据
里面的元素都是字符[长度为1的字符串]
‘a’ ‘b’ ’ ’ ‘0’
不可变的有序序列
s = 'hello everyone'
# 获取元素个数
print(len(s))
# 可以通过下标 获取字符
print(s[0])
print(s[-1])
print(s[:3])
print(s[-3:])
# s[0] = 'H'
# TypeError: 'str' object does not support item assignment
获取的操作
1. 字符串数据.find(子串)
查找子串第一次出现的位置
2. 字符串数据.rfind(子串)
查找子串最后一次出现的位置
3. 字符串数据.count(子串)
统计子串出现的次数
s = 'hello everyone'
pos = s.find('e')
print(pos) # 1
pos = s.rfind('e')
print(pos) # 13
count = s.count('e')
print(count)
转换的操作
将字符串中的相关符号进行转换 【因为字符串不可变 产生的数据是影响不了原本的数据 都是产生的是一个新的数据】
字符串数据.upper() 将字母变大写
字符串数据.lower() 将字母变小写
字符串数据.swapcase() 将大写变小写 将小写变大写
字符串数据.title() 每个单词首字母大写 【单词:没连接在一起的就视作一个新的单词】
字符串数据.capitalize() 首字母大写 其他小写
s = 'hello everyone'
new_s = s.upper()
print(s, new_s)
new_s1 = new_s.lower()
print(new_s1)
new_s2 = new_s.title()
print(new_s2) # Hello Everyone
new_s3 = new_s2.swapcase()
print(new_s3)
new_s4 = new_s3.capitalize()
print(new_s4)
判断的操作
1. 是否以指定内容开头
字符串数据.startswith(指定内容)
2. 是否以指定内容结尾
字符串数据.endswith(指定内容)
3. 判断是否是纯数字
字符串数据.isdigit()
4. 判断字符串的内容是否为纯字母
字符串数据.isalpha()
5. 判断字符串的内容是否为数字或字母
字符串数据.isalnum()
6. 判断字符串中的字母是否为大写
字符串数据.isupper()
7. 判断字符串中的字母是否为小写
字符串数据.islower()
s = 'Hello Everyone'
print(s.startswith('H'))
print(s.endswith('one'))
print(s.isalnum()) # False
print(s.isalpha()) # False
print(s[0].isupper()) # True
print(s[-3:].islower()) # True
print('123'.isdigit())
print('abc12'.isdigit())
练习:
data = "hello my age is 18, my birthday is September 5th."
1.遍历字符串 提起其中的数字符号
2.将字符串中首字母大写 其他小写
3.统计字符串中a出现的次数
4.查找is第一次出现的位置 并从这个位置一直提取到最后
data = "hello my age is 18, my birthday is September 5th."
digit_s = '' # 空字符串
for ch in data:
# 判断是否为数字
if ch.isdigit():
# 字符串的+号运算
digit_s = digit_s + ch
print(digit_s)
# 2.将字符串中首字母大写 其他小写
print(data.title())
# 统计字符串中a出现的次数
print(data.count('a'))
# 4.查找is第一次出现的位置 并从这个位置一直提取到最后
print(data[data.find('is'):])
字符串的切割与拼接
切割:
字符串数据.split(切割符)
将指定切割符为切割点 把字符串分成N份, 结果是一个列表 存储多个子串
拼接:
‘拼接符’.join(容器型数据)
使用拼接符将容器中的元素拼接在一起
注意:容器中的元素必须是字符串类型的 底层实现的时候 使用的是 +号运算
+在字符串中完成的字符串拼接 只能拼接字符串类型的
print(data)
print(data.split(' '))
# ['hello', 'my', 'age', 'is', '18,', 'my', 'birthday', 'is', 'September', '5th.']
print(data.split('e'))
nums = [18, 34, 56, 71, 29]
# 使用+号将其拼接在一起
# print('+'.join(nums))
# TypeError: sequence item 0: expected str instance, int found
# 人家期待的是字符串 但是获取的却是整型
# 拼接之前转化成字符串
# str(nums) # 将传进的数据转化为字符串 ====> '[18, 34, 56, 71, 29]'
str_nums = [str(ele) for ele in nums] # ['18', '34', '56', '71', '29']
print('+'.join(str_nums)) # 18+34+56+71+29
字符串格式化
在指定宽度中居中显式 字符串.center(宽度, 占位符)
在指定宽度中居左显式 字符串.ljust(宽度, 占位符)
在指定宽度中居右显式 字符串.rjust(宽度, 占位符)
s = 'hello'
print(s.center(10, '*'))
print(s.ljust(10, '*'))
print(s.rjust(10, '*'))
将未知的数据格式化拼接在字符串文本中
目的:将非字符串类型的数据与字符串类型的数据进行拼接
# + 可以让字符串进行拼接 但是只能字符串类型的数据
# print('年龄' + 17)
# TypeError: can only concatenate str (not "int") to str
# 只能字符串与字符串进行拼接
方式1 将数据转化为字符串类型
print('年龄' + str(17))
方式2: 使用字符串中 % 运算符 【% 在数字运算是取余】
先生成文本 在未知的位置使用占位进行占位,再对字符串进行%, 给占位的符号赋值
占位符:
%s — 可以填充任意类型的数据
%d — 填充的是整型数据
可以单独再进行格式化操作
%0nd === n代表的是数字显式的宽度 不足n位 左边补充0
%05d ====> 10 ====> 显式的时候 为 00010
%f — 填充的浮点型数据
可以再单独格式化
%.nf === n代表的是保留小数的位数
%.3f ====> 3.1415926 ===>显式为 3.142
year = 2020
month = 4
if month in (4, 6, 9, 11):
day = 30
elif month in (1, 3, 5, 7, 8, 10, 12):
day = 31
else:
if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):
day = 29
else:
day = 28
# 有几个占位符 就赋予几个值 值和占位符之间是一一对应的
content = '%s年%s月有%s天' % (year, month, day)
print(content)
# 学号 显式的时候按照6位来显式
sid = 1
# 姓名
name = '张三'
# 年龄
age = 17
# 成绩 显式的时候保留一位小数
score = 89.65
info = '学号为%06d的%s,年龄是%s, 考试成绩为%.1f' % (sid, name, age, score)
print(info)
方式3: 字符串数据.format()
先生成字符串文本数据,未知数据的地方使用 {}进行占位 调用字符串的format操作 给占位符进行赋值
有几个占位符 传递就有几个值
如果对数据有特殊的格式 在{}操作
{:0nd} 按照n位填充
{:.nf} 保留n位小数
info1 = '学号为{:06d}的{}, 年龄是{}, 考试成绩为{:.1f}'.format(sid, name, age, score)
print(info1)
方式4: 是方式3的简化 使用f修饰字符串
f修饰完字符串 可以直接在{}的位置填充对应的数据值
要修饰数据 {数据:0nd} {数据:.nf}
info2 = f'学号为{sid:06d}的{name}, 年龄是{age}, 考试成绩是{score:.1f}'
print(info2)
31_字典
存储一天温度变化记录 使用的一个列表进行存储的
7点 9点 11点 2点 4点 6点
为了更方便表达数据的含义,可以使用字典来进行存储
{key:value, key:value}
会给每一个数据设置标记, 通过标记名获取对应的数据值
字典是使用键值对进行数据的存储,是通过键定位值的,要求键是不允许重复的, 键的内容一旦确定不允许发生变换
字典是无序的可变序列
无序:代表元素没有位置编号,也就是不同过下标获取数据 只能通过键获取数据值
可变:数据值可以修改 可以增加新的键值对 删除键值对
air_temp = {'7点': 17, '9点': 20, '11点': 26, '14点': 30, '16点': 25, '18点': 22}
print(air_temp)
获取数据的话通过标记名取值
print(air_temp['11点'])
# 如果键不存在就报错
# print(air_temp['10点'])
# KeyError: '10点'
获取数据值推荐方式
print(air_temp.get('11点'), air_temp.get('10点')) # 26 None
获取键值对的个数
print(len(air_temp)) # 6
添加新的键值对
air_temp.setdefault('19点', 20) # 影响的是原数据
print(air_temp)
移除键值对
air_temp.pop('11点')
print(air_temp)
修改
air_temp['19点'] = 18
print(air_temp)
清除
air_temp.clear()
遍历
直接遍历字典 遍历的是字典中的键 [直接对字典进行成员操作 获取的是键]
for ele in air_temp:
print(ele, air_temp.get(ele))
# 等价于
print(air_temp.keys()) # 字典中所有的键 dict_keys(['7点', '9点', '14点', '16点', '18点', '19点'])
for k in air_temp.keys():
print(k)
单独拿值
print(air_temp.values()) # dict_values([17, 20, 30, 25, 22, 20])
for v in air_temp.values():
print(v)
获取字典中键值组合
print(air_temp.items()) # dict_items([('7点', 17), ('9点', 20), ('14点', 30), ('16点', 25), ('18点', 22), ('19点', 20)])
for item in air_temp.items():
print(item)
print('============')
for k, v in air_temp.items():
print(k, v)
32_字典的案例
词频统计
词/字符/数字 出现的个数 或者对数据进行归类
s = 'good good study day day up'
print(s)
"""
统计每个字符出现的个数 字符-个数 ====》 使用字典类型展示数据
思路:
1. 遍历字符串 获取每个字符
2. 把字符出现的个数存储字典中 字符与个数的信息 【字符为键 个数为值】
把遍历到的字符作为键 个数作为值存放于字典中
"""
count_dict = {} # 空字典 因为不知道最终有多少个键值对
for ch in s: # 遍历获取每个字符
# 逻辑
if ch not in count_dict: # 直接对字典使用成员运算 获取的是键
# 代表第一次出现
count_dict.setdefault(ch, 1)
else:
# 次数+1
count_dict[ch] = count_dict.get(ch) + 1
print(count_dict)
归类
nums = [19, 27, 38, 41, 25, 66, 24, 32, 51]
# 偶数为一类 奇数为一类
# 字典中会有两组键值对 值为什么是[] 因为偶数是什么 有多少个不知道 奇数是什么 有多少个 也不知道
# 但是肯定是多个的 所以放一个可变的容器
classify_dict = {'even': [], 'odd': []}
# 遍历
for ele in nums:
if ele % 2 == 0:
classify_dict['even'].append(ele)
else:
classify_dict['odd'].append(ele)
print(classify_dict)
每一类的数据的个数
classify_dict1 = {'even': 0, 'odd': 0}
# 遍历
for ele1 in nums:
if ele1 % 2 == 0:
classify_dict1['even'] += 1
else:
classify_dict1['odd'] += 1
print(classify_dict1)
"""
练习:
1. data = "hello nice to meet you nice to meet you too good fine nice"
统计每个单词出现的个数
2. nums = [82, 71, 65, 43, 29, 72, 64, 58, 87, 39]
将十位大于个位的归为一类 另外一种自成一类
"""
data = "hello nice to meet you nice to meet you too good fine nice"
# 获取单词
words = data.split(' ')
print(words)
count_dict1 = {}
for w in words:
if w not in count_dict1:
count_dict1.setdefault(w, 1)
else:
count_dict1[w] += 1
print(count_dict1)
nums = [82, 71, 65, 43, 29, 72, 64, 58, 87, 39]
classify_dict2 = {'gt': [], 'other': []}
for ele2 in nums:
if ele2 // 10 % 10 > ele2 % 10:
classify_dict2['gt'].append(ele2)
else:
classify_dict2['other'].append(ele2)
print(classify_dict2)
字典数据的过滤
dict0 = {'hello': 1, 'nice': 3, 'to': 2, 'meet': 2, 'you': 2, 'too': 1, 'good': 1, 'fine': 1}
print(dict0)
# 找到次数为1的单词信息 以键值对形式展示
new_dict = {}
for k, v in dict0.items():
if v == 1:
new_dict.setdefault(k, v)
print(new_dict)
字典推导式
注意:字典中存放饿是键值对 key:value
print({k: v for k, v in dict0.items() if v == 1})
单词中包含e的词频信息
new_dict1 = {}
for k, v in dict0.items():
if 'e' in k:
new_dict1.setdefault(k, v)
print(new_dict1)
print({k: v for k, v in dict0.items() if 'e' in k})