IT数码 购物 网址 头条 软件 日历 阅读 图书馆
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
图片批量下载器
↓批量下载图片,美女图库↓
图片自动播放器
↓图片自动播放器↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁
 
   -> Python知识库 -> 学习python第十一天 -> 正文阅读

[Python知识库]学习python第十一天

学习python第十一天

一周总结

本周我们主要学习来一下内容

  • 列表

  • 元组

  • 字符串

  • 集合

  • 字典

    主要学习掌握他们的各项操作和功能

    首先是列表

列表

列表支持,增、删、改、查等功能,

切片
  • 语法------>[start : end: step]

  • 切片类别:局部切片,全部切片,有步长和无步长,还有反向切片

运算
  • 重复运算------>输出列表

  • 成员运算------>输出布尔值

  • 合并运算------->输出列表

  • 比较------------>输出布尔值

功能
  • 添加元素常用的两种方法----->instert, appdend

  • 删除元素常用的两种方法----->pop, remove

  • 清空列表--------------------------->clear

  • 切片也算查找元素,还有索引查找

使用列表
  • 反转列表

    使用反向切片, 或者直接使用函数

    items = items[::-1]
    print(items)
    items.reverse()
    print(items)
    
  • 给列表排序

    注意要求正序还是倒序

    默认为正序

    items.sort(reverse=False)
    print(items)
    items.sort(reverse=True)
    print(items)
    
  • 格式化定义列表

    • 直接循环一个数字区间
    • 有条件的从一个数字区间挑选
    • 从一个数字区间随机挑选
    nums = [i for i in range(1, 10)]
    nums = [i for i in range(1, 100) if i % 5 == 0 or i % 3 == 0]
    nums = [random.randrange(1, 100) for _ in range(10)]
    

    练习

    • 简单选择排序------>每次从剩下的元素中选择最小值

nums = [35, 12, 99, 58, 67, 42, 49, 31, 73]

nums = [35, 12, 99, 58, 67, 42, 49, 31, 73]
for i in range(len(nums) - 1):
    # 假设第一个元素就是最小值
    min_value, min_index = nums[i], i
    # 通过循环寻找有没有更小的值并记下他的位置
    for j in range(i + 1, len(nums)):
        if nums[j] < min_value:
            min_value, min_index = nums[j], j
            # 将最小的值换到前面的位置
    nums[i], nums[min_index] = nums[min_index], nums[i]
print(nums)

  • 冒泡排序------>元素两两比较,如果前面的元素大于后面的元素,就交换两个元素的位置
    nums = [35, 12, 99, 58, 67, 42, 49, 31, 73]

    加上一个条件识别是否提前将列表排好序

    nums = [2, 3, 4, 5, 6, 7, 8, 9, 1]排一次即可

    通过验证第二次循环时有无元素交换位置推测列表是否将顺序排好

    例如特殊情况

nums = [35, 12, 99, 58, 67, 42, 49, 31, 73]
for i in range(1, len(nums)):
    swapped = False
    for j in range(0, len(nums) - i):
        if nums[j] > nums[j + i]:
            nums[j], nums[j + i] = nums[j + i], nums[j]
            swapped = True
    if not swapped:
        break
print(nums)

抽样和乱序

  • 函数无放回抽样sample

  • 函数可以对列表多个元素元素同时进行又放回抽样,(可以重复抽中)choices

  • 函数可以从列表中随机抽取一个元素choice

  • 使用函数将列表中元素顺序随机打乱,random.shuffle()

元组

不可变的容器,注意一元组一定要有一个逗号否则会被认为是一个字符串,元组只支持查看,

运算

元组的运算不会改变原有元组只会形成新的元组, 与列表输出效果相同

  • 成员运算
  • 重复运算
  • 合并运算

其他

  • 索引和切片(与列表格式相同)

  • 查找元素所在的索引 fruits3.index()

  • 计算元素在元组中出现的次数 fruits3.count()

字符串

注意:字符串也是不变数据类型,只能进行读操作,不能进行改写操作

运算

字符串的运算不会改变原有元组只会形成新的字符串, 与列表输出效果相同

  • 重复运算
  • 成员运算
  • 比较运算

字符串的操作

大小写转换
  • 转大写
    print(a.upper())

  • 转小写
    print(a.lower())

  • 首字母大写
    print(a.capitalize())

  • 每个单词首字母大写
    print(a.title())

检测字符串
在字符串中查找有没有某个子串的操作
index / rindex
find / rfind
字符串放置
# 居中
print(a.center(80, '='))
# 右对齐
print(a.rjust(80, '='))
# 左对齐
print(a.ljust(80, '='))

b = '1234'
# 零填充(在左边补0)
print(b.zfill(6))
# 修建左边空格
print(email.strip())
# 袖箭右边空格
print(email.rsplit())
# 将指定的内容用。。。替换
print(meat.lstrip('替换内容').replace('替换内容', '*'))
分解和连接字符串
content = 'You go your way, I will go mine.'
content2 = content.replace(',', '').replace('.', '')
# 去掉字符串中的指定元素,这里是逗号和句号
print(content2)
# 拆分字符串
words = content2.strip()
for word in words:
    print(word)
# 用逗号拆分字符串
words = content2.strip(',')
for word in words:
    print(word)
# 用空格拆分字符串,最多拆分三次
items = content2.split(' ', maxsplit=3)
print(items, len(items))
# 从右到左用空格拆分字符串,最多拆分三次
item = content2.rsplit(' ', maxsplit=3)
print(item, len(items))

contents = [
    '请不要相信我的美丽',
    '更不要相信我的爱情',
    '因为在涂满油彩的面孔下',
    '有着一颗戏子的心'
]
# 将列表中的元素用指定的字符串连接起来
print(','.join(contents))

转换字符串编码

编码:把一种字符串集转换成另外一种字符集
解码:把一种字符集转换成另外一种字符串集
要点:
1、选择字符集编码时,最佳选择也是默认的是utf-8编码
2、编码和解码的字符集要保持一致,否则会出现乱码现象
3、不能用ISO-8859-1编码保存中文,否则会出现编码黑洞,中文变成问号
4、UTF-8是Unicode的一种实现方案, 也是一种变长的编码,最少一个字节,最多四个字节,表示中文用三个字节

5、如果编码和解码的方式不一样,python中可能会产生UnicodeDecodeError异常

6、也有可能出现乱码现象

字符串加密

例如凯撒密码

凯撒密码 - 通过对应字符的替换,实现对明文进行加密的一种方式
abcdefghijklmnopqrstuvwxyz
defghijklmnopqrstuvwxyzabc
明文:attack at dawn
密文:dwwdfn dw gdzq
对称加密: 机密和解密使用了相同的密钥
非对称加密: 加密和解密使用不同的密钥(公钥、私钥)---->适合互联网应用

message = 'attack at dawn'
# 生成字符串转换的对照表
table = str.maketrans('abcdefghijklmnopqrstuvwxyz',
                      'defghijklmnopqrstuvwxyzabc')
# 字符串的translate方法实现字符串转换
print(message.translate(table))

集合

集合的定义和中学时学习的集合定义大致相同

集合的运算

  • 成员运算------>输出布尔值

  • 交集运算------->set1 & set2、、set1.intersection(set2

  • 并集运算------->set1 | set2、、set1.union(set2)

  • 差集运算------->set1 - set2、、set1.difference(set2)

  • 对称差---------->set1 ^ set2、、(set1 | set2) - (set1 & set2)、、set1.symmetric_difference(set2)

集合的操作

set1 = {'apple', 'banana', 'strawberry'}
print(set1)
# 添加元素
set1.add('blueberry')
set1.add('waxberry')
print(set1)
# 删除元素(随机)
print(set1.pop())
print(set1)
# 删元素,指定删除
set1.discard('apple')
# 清空集合
set1.clear()

字典

元素由键和值构成,冒号前面称为键,冒号后面称为值

创建字典语法

  • 字面量语法

  • 构造器语法

  • 生成式语法

遍历字典

  • 遍历字典中的键
  • 遍历字典中的值
  • 遍历字典中的键和值

字典的相关操作

注意:

1、字典的索引运算放在赋值运算的左边,
2、如果索引对应的键存在,就更新它的值
3、如果字典中没有对应的索引,就增加一组新的键值对

4、合并键值对,相同的键就更新

5、删除元素, 键必须要存在否则会报错

# 默认删除最后一项
dict1.popitem()
# 清空字典
dict2.clear()
print(dict1)
dict1.setdefault('C', 800)  # 这里没啥用
print(dict1)
dict1.setdefault('F', 1000)  # 这里加入一个键值对
print(dict1)

相关题目总结

选择几个典型的讲解

简单排序
nums = [35, 12, 99, 58, 67, 42, 49, 31, 73]
for i in range(len(nums) - 1):
    # 假设第一个元素就是最小值
    min_value, min_index = nums[i], i
    # 通过循环寻找有没有更小的值并记下他的位置
    for j in range(i + 1, len(nums)):
        if nums[j] < min_value:
            min_value, min_index = nums[j], j
            # 将最小的值换到前面的位置
    nums[i], nums[min_index] = nums[min_index], nums[i]
print(nums)
冒泡排序
nums = [35, 12, 99, 58, 67, 42, 49, 31, 73]
for i in range(1, len(nums)):
    for j in range(0, len(nums) - i):#循环n-1ci
        if nums[j] > nums[j + i]:#比较大小
            nums[j], nums[j + i] = nums[j + i], nums[j]#把大的放在后面
print(nums)


#特殊情况
nums = [9, 2, 3, 4, 5, 6, 7, 8]
for i in range(1, len(nums)):
    swapped = False
    for j in range(0, len(nums) - i):
        if nums[j] > nums[j + i]:
            nums[j], nums[j + i] = nums[j + i], nums[j]
            swapped = True
    if not swapped:
        break
print(nums)



nums = [2, 3, 4, 5, 6, 7, 8, 9, 1]
for i in range(1, len(nums)):
    swapped = False
    for j in range(0, len(nums) - i):
        if nums[j] > nums[j - i]:
            nums[j], nums[j - i] = nums[j - i], nums[j]
            swapped = True
    if not swapped:#当swapped不再改变是,即为False时结束
        break
print(nums)
幸运的女人问题

15个男人和15个女人同时在一艘船上在海里。现在船坏了,需要将15个人扔下去,其他的15个人才能获救。,于是把15个男人和15个女人顺序打乱围成一个圆圈。。指定一个人为第一个。从一数到九。数到第九的那个人就被扔下海里。求与人的位置是什么,才能保证15个女人都在船上,数到酒之后,从头开始数

persons = [True] * 30
index, counter, number = 0, 0, 0
# 索引, 计数器,报数
while counter < 15:#用丢进海里的人数作为停止循环的钥匙
    if persons[index]:
        number += 1
        if number == 9:
            persons[index] = False#数到九被丢进海里
            counter += 1#被丢进海里的人数加一
            number = 0
            pass
    index += 1
    if index == 30:
        index = 0#当最后一个人报完数后,索引又从头开始
for person in persons:
    # if person:
    #     print('女', end='')
    # else:
    #     print('男', end='')
    # 三元条件运算----->if后面的表达式为True,取if前面的值, 否则取else后面的值
    print('女' if person else '男', end='')#相当于上面注释部分
    
    
    
    #简化版
person = [i for i in range(30)]#将30个人依次放入列表
for _ in range(15):
    person = person[9:0] + person[:8]#每隔9切片,将9前后的列表切片相加,前面的放在后面,形成一个新的列表再次以相同的方式切片,循环15次即可
for i in range(1, 31):
    print('女' if i in person else '男', end='')

发牌问题
import random
porke_numbers = [i for i in range(2, 11)]
flower_porkes = ['A', 'J', 'Q', 'K']
porke_numbers += flower_porkes
#确定相同花色的牌种扑克牌种类,2~10、AJKQ
# print(porke_numbers)
porke_nums = []
color_porkes = ['?', '?', '?', '?']#花色,使用计算机自带输入法可以打出来
for color_porke in color_porkes:#遍历花色
    for porke_number in porke_numbers:#遍历扑克数字
        porke_nums.append(color_porke + str(porke_number))#将花色和数字组合
        # porke_nums.append(f'{color_porke}{porke_number}')
# porke_nums = [f'{color_porke}{porke_number}' for color_porke in color_porkes for porke_number in porke_numbers ]
porke_nums.append('大王')
porke_nums.append('小王')
# print(porke_nums)
random.shuffle(porke_nums)#使用打乱列表元素顺序
# print(porke_nums)
# print(len(porke_nums))
# player1.append(porke_nums[51:54])
# print(player1)
player1 = []
player2 = []
player3 = []
for i in range(0, len(porke_nums) - 3, 3):#减三将后面三张给第一个玩家
    player1.append(porke_nums[i])# 循环一次取三张扑克,所以循环步长为三
    player2.append(porke_nums[i + 1])
    player3.append(porke_nums[i + 2])
player1 += porke_nums[52:54]#,将后面三张给第一个玩家

# for _ in range(17):
#     player1.append(porke_nums.pop())
#     player2.append(porke_nums.pop())
#     player3.append(porke_nums.pop())
# player1 += porke_nums
# player1.extend(porke_nums)
player1.sort(key=lambda x: x[1:])#这里可以不知道原理,知道作用就行,后面才会学到,作用是比较发到手里扑克大小将其整理好
player2.sort(key=lambda x: x[1:])
player3.sort(key=lambda x: x[1:])
for card in player1:
    print(card, end=' ')
print()
for card in player2:#遍历玩家手里的扑克将其输出
    print(card, end=' ')
print()
for card in player3:
    print(card, end=' ')
print()

#简化输出格式
去重复元素
nums = [2, 3, 4, 5, 6, 7, 8, 9, 4, 5, 5, 3, 3, 8, 6, 9]
counts = []
for num in nums:
    if num not in counts:# 如果原列表中的元素,空列表里面没有,就往空列表里添加这元素,
        counts.append(num)
print(counts)

找出现次数最多的重复元素

注意:可能不止一个

nums = [2, 3, 4, 4, 4, 5, 6, 7, 8, 9, 4, 5, 5, 3, 3, 8, 6, 3, 3, 4]
sum = []#定义空列表装出现最多的元素
max_apper = nums.count(nums[1])#首先假定第一个元素出现次数最多
for num in nums:#循环列表一次比较各个元素出现的次数
    if max_apper < nums.count(num):#将出现次数多的次数赋值给初始值
        sum.clear()#找到新的出现最多的元素就要把以前存起来的元素清理掉
        max_apper = nums.count(num)#将新元素装进列表
        sum.append(num)
    elif max_apper == nums.count(num):
        if num not in sum:#如果找到与目前最多出现次数相同的,且不是同一个元素,就一同放进列表,
            sum.append(num)

print(f',出现最多的元素是{sum}输出了{max_apper}次')
杨辉三角形
nums = [1]
for _ in range(0, 20):
    order = []
    print(nums)
    for j in range(0, len(nums) + 1):
        if j == 0:
            order.append(nums[j])
        elif j == len(nums):
            order.append(nums[len(nums) - 1])
        else:
            order.append(nums[j] + nums[j - 1])
    nums = order
查找问题

输入一段英文,用字典表示每个字母出选的次数大小写归一类以

man is distinguished, not only by his reason, but by this singular passion from other animals, which is a lust of the mind, that by a perseverance of delight in the continued and indefatigable generation of knowledge, exceeds the short vehemence of any carnal pleasure.为例

import string
sces = 'man is distinguished, not only by his reason, but by this singular passion from other animals, which is a lust of the mind, that by a perseverance of delight in the continued and indefatigable generation of knowledge, exceeds the short vehemence of any carnal pleasure.'
dict1 = {i: 0 for i in string.ascii_lowercase}# 格式化输出,将26个字母导入字典成为字典的键,而字典的值都是0
for sce in sces:
    if sce in dict1:
        sces.count(sce)# 计算字母出现的次数
        dict1[sce] = sces.count(sce)
for key, value in dict1.items():
    print(f'{key} {value}')

股票分析
stocks = {
    'AAPL': 191.88,
    'GOOG': 1186.96,
    'IBM': 149.24,
    'ORCL': 48.44,
    'ACN': 166.89,
    'FB': 208.09,
    'SYMC': 21.29
}
stocks1_new1 = {key: value for key, value in stocks.items() if value > 100}
print(stocks1_new1)
print(max(zip(stocks.values(), stocks.keys()))[1])
# 将字典的键和值交换顺序打包起来就形成二元组,元组就可以使用max、min函数
# 而且打包的时候交换顺序就是为了直接比较他们的值,然后找出值最大的,一行代码直接搞定键值对,此时的键值对值在前面键在后面,而我们要的是键,所以,数到第二个,索引为一
print(min(zip(stocks.values(), stocks.keys()))[1])
print(max(stocks, key=stocks.get))
# 这个更牛,直接比较值,虽然max,min不能直接用于比较键值对,但却可以选择性的比较啊,max函数,然后直接指定键对应的值进行比较
print(min(stocks, key=stocks.get))
print(sorted(stocks, key=stocks.get, reverse=True))
# 排序就和第二种找最大的方法大同小异,但是注意这里是sorted!!!!
print(sorted(stocks, key=stocks.get, reverse=False))

总结

这周的内容还是比较多的,但是如果每一天都认真学习,练习,分下来每一天的消化两也就大幅降低,一周的学习下来可能不会注意已经得到多少,但是周末的总结复习就可以将所学知识汇总,并且认识到自己掌握了多少,还有多少没有掌握就只要着重复习

认真总结了好久,留下你宝贵的赞👍再走吧

  Python知识库 最新文章
Python中String模块
【Python】 14-CVS文件操作
python的panda库读写文件
使用Nordic的nrf52840实现蓝牙DFU过程
【Python学习记录】numpy数组用法整理
Python学习笔记
python字符串和列表
python如何从txt文件中解析出有效的数据
Python编程从入门到实践自学/3.1-3.2
python变量
上一篇文章      下一篇文章      查看所有文章
加:2021-08-01 14:27:47  更:2021-08-01 14:29:58 
 
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁

360图书馆 购物 三丰科技 阅读网 日历 万年历 2024年5日历 -2024/5/19 7:32:27-

图片自动播放器
↓图片自动播放器↓
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
图片批量下载器
↓批量下载图片,美女图库↓
  网站联系: qq:121756557 email:121756557@qq.com  IT数码