• 新手Python第二天(存储)


    Python 列表的创建

      创建一个空列表    例如:fruit=[] 
      创建一个有元素的列表 例如:fruit=['apple','banana','cherry'] 

      创建嵌套列表     例如:fruit=[['apple','1'],['banana','2'],['cherry','3']] 

    Python 列表元素的查找

    fruit=['apple','banana','cherry']
    print(fruit)    #获取全部元素
    print(fruit[:-1])#等同于上方的效果
    print(fruit[:])  #等同于上方的效果
    print(fruit[0])  #单个元素的获取
    print(fruit[0:3])#实际获取0~2下标之间的元素(顾首不顾尾)
    print(fruit[:3]) #等同于上方的效果
    print(fruit[-1]) #获取倒数第一个元素
    print(fruit[-2:-1])#只获取倒数第二个元素
    print(fruit[-2:])#从倒数第二个获取到最后
    View Code

    Python 列表元素的添加和修改

    fruit.append('pear')   #在列表的最后添加元素
    fruit.insert(1,'grape')#在下标1的位置添加元素,其他元素后移一位
    fruit[0]='tomato'     #元素的替换
    View Code

    Python 列表元素的删除

    fruit.remove('tomato') #使用名称移除一个元素
    del fruit[0]           #使用下标移除元素
    fruit.pop(index=0)     #效果同上,默认移除最后一个
    fruit.clear()          #清空列表所有的元素
    View Code

    Python 列表其他函数

    print(fruit.index('apple'))#下标的查找
    print(fruit.count('apple'))#元素个数的统计
    fruit.sort()#按照ASCII码排序
    fruit.reverse() #反转列表
    fruit.extend([1,2,3])#添加列表到fruit列表尾部
    fruit2=fruit.copy() #第一层独立复制,第二层复制的是内存地址
    fruit2=fruit[:]       #同上
    fruit2=list(fruit)    #同上
    import copy
    fruit2=copy.deepcopy(fruit)#真正的完全复制
    View Code

     Python 列表的循环

    for i in fruit:
        print(i)
    for i in range(len(fruit)):
        print(fruit[i])
    for index,data in enumerate(fruit):
        print(index,data)
    View Code

    Python 元组的创建

      创建一个空元组    例如:fruit=() 
      创建一个有元素的元组 例如:fruit=('apple','banana','cherry')

    Python 元组的使用

      元组是一个只读列表不可用添删改,但是可以查询(通上方列表的查找)


    Python 字典的创建

      创建一个空字典       例如:fruit={}

      创建一个有元素的字典 例如:fruit={'one':'apple','two':'banana','three':'cherry'}

      创建一个嵌套字典   例如:fruit={'one':{'apple':'1'},'two':{'banana':'1'},'three':{'cherry':'1'}}

      创建一个联合字典        例如:fruit=dict.fromkeys(['1','2',3],{'name':'gm'})#和上方列表的copy方法相似

    Python 字典的查询

    fruit={'one':'apple','two':'banana','three':'cherry'}
    print(fruit['one'])#获取值,但没有'one'的时候会报错
    print(fruit.get('one'))#获取值
    print(fruit.keys())#获取所有的键
    print(fruit.values())#获取所有的值
    View Code

    Python 字典的修改

    fruit['four']='pear'#如果'four'存在这修改,不存在就创建
    fruit.update({'one':'apple juice','five':'petter'})#如果有就修改,没有就添加
    fruit.setdefault('one','apple core')#如果'one'存在不修改,不存在创建
    View Code

    Python 字典的删除

    del fruit['one']#指定删除,但没有one会报错
    fruit.pop('one')#指定删除,同样没有'one'会报错
    fruit.popitem()#随机删除
    fruit.clear() #清空字典
    View Code

    Python 字典其他函数

    fruit.items()#转换成列表
    fruit.copy()#同列表的copy一样
    View Code

    Python 字典的循环

    for i in fruit:
        print('key:%s value:%s'%(i,fruit[i]))
    for k,val in fruit.items(): #不建议使用效率低
        print(k,val)
    View Code

    Python 集合的创建

      创建一个有元素的集合 例如:gather_one=set([1,2,3,4,4])

    Python 集合的关系

    gather_one=set([1,2,3,4,4])
    gather_one_son=set([1,2,3])
    gather_two=set([3,4,5,6])
    print(gather_one.intersection(gather_two))#交集
    print(gather_one.symmetric_difference(gather_two))#反向交集
    print(gather_one.union(gather_two))#并集
    print(gather_one.difference(gather_two))#差集
    print(gather_one.issuperset(gather_one_son))#子集
    print(gather_one_son.issubset(gather_one))#子集
    View Code

    Python 集合的添加

    gather_one.add(15)#添加一个集合元素
    gather_one.update([100,222,333])#添加多个元素
    View Code

    Python 集合的删除

    gather_one.pop()#随机删除一个集合元素
    gather_one.discard(15)#删除一个集合元素
    gather_one.remove(2)#删除一个指定集合元素
    View Code

    Python 集合的其他函数

    gather_three=gather_one.copy()#和列表的复制效果相同
    print(gather_one)
    View Code

     Python 字符串的判断

    fruit='cherry'
    print('1.2'.isdigit())#判断是否是正整数
    print('1a'.isalnum())#判断是否是数字和英文字母(不包含特殊字符)
    print('1a'.isalpha())#判断是否是纯英文字符
    print('1A'.isdecimal())#判断是否为十进制
    print('1a'.isidentifier())#判断是不是合法的变量名
    print('a1'.islower())#判断是否有小写
    print(fruit.isnumeric())#判断是否是正整数
    print(fruit.isprintable())#判断是否是打印文件
    print(fruit.isspace())#判断是否是空格
    print(fruit.istitle())#判断每个开头字母是否为大写
    print(fruit.isupper())#判断是否为大写
    print(fruit.endswith('ry'))#判断是否是'ry'结尾
    print(fruit.startswith('ch'))#判断是否是'ch'开头
    View Code

    Python 字符串的转化

    print(fruit.lower())#全部小写
    print(fruit.upper())#全部大写
    print('AbCd'.swapcase())#大小写互换
    print(fruit.capitalize()) #首字母大写
    print(fruit.title())#每个单词的首字母大写
    print(fruit.encode(encoding='utf8')) #字符串转化成bytes类型
    print(b'aaa'.decode(encoding='utf8'))#bytes类型转化成字符串
    View Code

    Python 字符串的格式化

    print('my name is {name}'.format(name=fruit))#格式化
    print('my name is {name}'.format_map({'name':fruit}))#格式化,可以使用字典带入
    print('+'.join(['1','2','3']))#拼接字符使用
    print('a b c d'.split(' '))#按照空格转化成列表默认空格
    print('a\nb\n'.splitlines())#按照系统默认回车符号转化成列表,windws(\r\n),linux(\n)
    print(' \npear'.lstrip())#去掉左边的全部空格和换行
    print('pear \n'.rstrip())#去掉右边的全部空格和换行
    print(' \npear \n'.strip())#去掉左右两边的全部空格和换行
    View Code

    Python 字符串的查找和替换

    print(fruit.find('c'))#查找字母下标,不存在返回-1
    print('abcda'.rfind('a'))#从右向左查找
    print('abcda'.replace('a','1',2))#替换字母'a'需要替换的字母,'1'替换后的字母,2替换几次
    p=str.maketrans('rry','***')#加密的方法
    print(fruit.translate(p))#使用上方方法加密
    View Code

    Python 字符串的补齐

    print(fruit.ljust(20,'-'))#总长度20,不足用'-'符号补齐,fruit左对齐
    print(fruit.rjust(20,'-'))#总长度20,不足用'-'符号补齐,fruit右对齐
    print(fruit.center(20,'-'))#总长度20,不足用'-'符号补齐,fruit居中
    print(fruit.zfill(20))##总长度20,不足用0补齐
    View Code

    Python 字符串的统计

    print(fruit.count('c')) #计算c在字符串中的个数

    Python 文件的打开

    f=open('file_test.text','r',encoding='utf8')#只读打开文件
    f=open('file_test.text','w',encoding='utf8')#写的方式打开文件(有这个文件就会覆盖)
    f=open('file_test.text','a',encoding='utf8')#追加的方式打开文件(append)
    f=open('file_test.text','r+',encoding='utf8')#读写方式,先读后写,写入以追加的模式
    f=open('file_test.text','w+',encoding='utf8')#写读,先写后读,写入以覆盖的方式
    f=open('file_test.text','a+',encoding='utf8')#追加读,
    f=open('file_test.text','rb',encoding='utf8')#以二进制的形式读取文件
    f=open('file_test.text','wb',encoding='utf8')#以二进制的形式写入文件
    f=open('file_test.text','ab',encoding='utf8')#以二进制的形式追加文件
    f=open('file_test.text','rU',encoding='utf8')#适配windows和linux的换行
    f=open('file_test.text','r+U',encoding='utf8')#适配windows和linux的换行
    View Code

    Python 文件的写入

    f.write('床前明月光,\n疑是地上霜,\n举头望明月,\n低头思故乡.')#写入
    f.writelines(['1','2','3'])#以类表的形式写入数据
    View Code

    Python 文件的读取

    print(f.readline())#读取一行
    print(f.read())#读取所有文件
    print(f.readlines())#读取所有变成列表的形式
    View Code

    Python 文件的关闭

    f.close()#关闭

    Python 文件的光标移动

    f.seek(0)#光标移动
    f.tell()#当前光标所在的位置
    View Code

    Python 文件的判断

    print(f.readable())#是否可读
    print(f.writable())#是否可写入
    print(f.seekable())#是否可移动光标
    print(f.closed)#是否可关闭
    f.isatty()#是不是一个终端设备
    View Code

    Python 文件的其他函数

    f.flush()#刷新内存中的文件保存
    f.truncate(10)#截断10个字符,10以后的字符会去掉
    f.fileno()#返回文件句柄的编号
    f.detach()#文件编辑过程中改变编码
    print(f.encoding)#文件的编码
    print(f.errors)#文件的报错
    View Code

    Python 文件的循环

    for line in f:          #最效率
        print(line.strip())
    for line in f.readlines():
        print(line.strip())
    View Code

    Python 编码的转换

    str='你好'
    #encode:编码 Python3中字符默认编码是'unicode'转换成'gbk'或者其他的编码
    print(str.encode('gbk'))
    #decode解码 'gbk'其他的编码转化成'unicode'编码
    print(str.encode('gbk').decode('gbk'))
    View Code

     Python 小试牛刀

      购物车程序的书写,思路:用户进入界面输入金额--->打印商品列表---->选择商品---->扣款---->加入购入车---->退出

    #coding=utf-8
    #Author:gm
    #readme:运行程序输入金额,进入商品列表,选择数字购买,按q退出
    commodity=[['apple','5'],['cherry','2'],['banana','1'],['grape','1']]
    shopping_car=[]
    #金额的输入
    while True:
        cash=input('你需要多少钱:')
        if cash.isdigit():
            break
        else:
            print('请输入正整数!')
    cash=int(cash)
    flag=True
    while cash>=0:
        #main
        #打印商品列表
        for i in range(len(commodity)):
            print('%s. %s 价格$%s'%(i+1,commodity[i][0],commodity[i][1]))
        print('你的金额:$%s'%(cash))
        commodity_id=input('购买:')
        #停止购买的条件
        if commodity_id=='q':
            break
        if commodity_id.isdigit():
            commodity_id = int(commodity_id)
        else:
            print('请输入正整数!')
            continue
        if commodity_id > len(commodity) or commodity_id < 1:
            print('没有件商品')
            continue
        comm_index = commodity_id-1
        #主要的逻辑判断
        if int(commodity[comm_index][1]) <= cash:
            shopping_car.append(commodity[comm_index])
            cash = cash - int(commodity[comm_index][1])
            print('成功购买%s'%(commodity[comm_index][0]))
        else:
            print('对不起你的金额不足')
    print('------你的购物车------')
    for i in shopping_car:
        print(i)
    print('你的余额$%s'%(cash))
    shopping_cart

     

    python学习途径

    友情推荐:  猿人学Python【https://www.yuanrenxue.com/】 由一群工作十余年的老程序员结合实际工作经验所写的Python教程。
  • 相关阅读:
    nginx学习(十):nginx搭建2台tomcat集群
    IOT设备SmartConfig实现
    AIDL原理分析
    MySQL升级-CentOS6.8
    CentOS更新yum源
    .net core微服务通信——gRPC(下)
    .net core微服务通信——gRPC(上)
    实时web应用方案——SignalR(.net core)
    redis常见Bug及雪崩、穿透、击穿解析
    asp.net core托管到windows服务
  • 原文地址:https://www.cnblogs.com/gm332211/p/8146066.html
Copyright © 2020-2023  润新知