zoukankan      html  css  js  c++  java
  • day2-python-模块列表字典

    一、模块

    sys

    #!/usr/bin/env python
    # -*- coding:utf-8 -*-
    import sys
    
    # print(sys.path) #打印环境变量
    print(sys.argv)

    os

    #!/usr/bin/env python
    # -*- coding:utf-8 -*-
    import os
    
    # cmd_res = os.system("dir")  #执行命令,不保存结果
    cmd_res = os.popen("dir").read()
    print("-->",cmd_res)
    os.mkdir("new_dir")

    二、数据类型

    1、数字

    int(整型)

      在32位机器上,整数的位数为32位,取值范围为-2**31~2**31-1,即-2147483648~2147483647
      在64位系统上,整数的位数为64位,取值范围为-2**63~2**63-1,即-9223372036854775808~9223372036854775807
    long(长整型)
      跟C语言不同,Python的长整数没有指定位宽,即:Python没有限制长整数数值的大小,但实际上由于机器内存有限,我们使用的长整数数值不可能无限大。
      注意,自从Python2.2起,如果整数发生溢出,Python会自动将整数数据转换为长整数,所以如今在长整数数据后面不加字母L也不会导致严重后果了。
    float(浮点型)
      浮点数用来处理实数,即带有小数的数字。类似于C语言中的double类型,占8个字节(64位),其中52位表示底,11位表示指数,剩下的一位表示符号。
    complex(复数)
      复数由实数部分和虚数部分组成,一般形式为x+yj,其中的x是复数的实数部分,y是复数的虚数部分,这里的x和y都是实数。
    2、布尔值
    真或假
    1或0
    三、三元运算

    result = 值1 if 条件 else 值2
    a,b,c=1,3,5
    d=a if a>b else c

    四、进制

    二进制,01
    八进制,01234567
    十进制,0123456789
    十六进制,0123456789ABCDEF

    五、列表

    1、创建列表

    names = ["hhh","aaa","bbb",["kkk","jjj"],"ccc","bbb"]

    names = list(["hhh","aaa","bbb",["kkk","jjj"],"ccc","bbb"])

    2、索引

    print(names)
    print(names[0],names[2])

    3、切片

    print(names[1:3]) 
    print(names[3])
    print(names[-2])
    print(names[-2:])
    print(names[:3])

    4、追加

    names.append("ddd") #末尾增加
    names.insert(1,"eee") #按位置增加
    names[2] = "fff" #替换

    5、删除

    names.remove("fff")
    # del names[1] = names.pop(1)
    names.pop(1)
    print(names)

    6、长度

    print(names.index("ccc"))
    print(names.count("bbb"))
    names.clear() #清空
    names.reverse() #反转
    names.sort() #排序

    7、循环

    for i in names:
        print(i)

    8、复制

    import copy
    name2 = names.copy()
    names2 = copy.deepcopy(names) #深复制,占用
    print(names)
    print(name2)

    9、包含

    names2 = [1,2,3,4]
    names.extend(names2)
    print(names,names2)

    六、元组

    元组其实跟列表差不多,也是存一组数,只不过它一旦创建,便不能再修改,所以又叫只读列表
    它只有2个方法,一个是count,一个是index

    ages = (11, 22, 33, 44, 55)
    或
    ages = tuple((11, 22, 33, 44, 55))

    七、程序:购物车程序

    需求:
    1、启动程序后,让用户输入工资,然后打印商品列表
    2、允许用户根据商品编号购买商品
    3、用户选择商品后,检测余额是否够,够就直接扣款,不够就提醒
    4、可随时退出,退出时,打印已购买商品和余额

    #!/usr/bin/env python
    # -*- coding:utf-8 -*-
    
    product_list = [
        ('Iphone',5800),
        ('Mac Pro',9800),
        ('Bike',800),
        ('Watch',10600),
        ('Coffee',31),
        ('Alex Python',120),
    ]
    shopping_list = []
    salary = input("Input your salary:")
    if salary.isdigit():
        salary = int(salary)
        while True:
            for index,item in enumerate(product_list):
                # print(product_list.index(item),item)
                print(index,item)
            user_choice = input("选择要买嘛?>>>:")
            if user_choice.isdigit():
                user_choice = int(user_choice)
                if user_choice < len(product_list) and user_choice >=0:
                    p_item = product_list[user_choice]
                    if p_item[1] <= salary: #买得起
                        shopping_list.append(p_item)
                        salary -= p_item[1]
                        print("Added %s into shopping cart,your current balance is 33[31;1m%s33[0m" %(p_item,salary))
                    else:
                        print("33[41;1m你的余额只剩[%s]啦,还买个毛线33[0m" %salary)
                else:
                    print("product code [%s] is not exist!"% user_choice)
            elif user_choice == 'q':
                print("----------shopping list------------")
                for p in shopping_list:
                    print(p)
                print("Your current balance:",salary)
                exit()
            else:
                print("invalid option")

    八、字符串

    #!/usr/bin/env python
    # -*- coding:utf-8 -*-
    
    name = "my 	name is {name} and i am {year} old"
    
    print(name.capitalize())    #首字母
    print(name.count("a"))
    print(name.center(50,"-"))
    print(name.endswith("ex")) #以什么结尾
    print(name.expandtabs(tabsize=30))
    print(name[name.find("name"):])
    print(name.format(name='alex',year=23))
    print(name.format_map({'name':'alex','year':12}))
    print('ab23'.isalnum())
    print('abA'.isalpha())
    print('1A'.isdecimal()) #十进制
    print('a 1A'.isidentifier()) #判读是不是一个合法的标识符
    print('a 1A'.islower())
    print('33.33'.isnumeric())
    print('My Name Is'.istitle())
    print('My Name Is'.isprintable())
    print('My Name Is'.isupper())
    print(''
          '+'.join(['1','2','3']))
    print(name.ljust(50,'*'))
    print(name.rjust(50,'-'))
    print('Alex'.lower())
    print('Alex'.upper())
    print('
    Alex'.lstrip())
    print('
    Alex
    '.rstrip())
    print('  
    Alex
    '.strip())
    p = str.maketrans("abcdef",'123456')
    
    print("alex li".translate(p))
    print('alex li'.replace('l','L',1))
    print('alex lil'.rfind('l'))
    print('1+2+3+4'.split('+'))
    print('1+2
    +3+4'.splitlines())
    print('Alex Li'.swapcase())
    print('lex li'.title())
    print('lex li'.zfill(50))

    九、字典(无序的)

    字典一种key - value 的数据类型,使用就像我们上学用的字典,通过笔划、字母来查对应页的详细内容。

    #!/usr/bin/env python
    # -*- coding:utf-8 -*-
    #key-value
    '''
    av_catalog = {
        "欧美":{
            "www.youporn.com": ["很多免费的,世界最大的","质量一般"],
            "www.pornhub.com": ["很多免费的,也很大","质量比yourporn高点"],
            "letmedothistoyou.com": ["多是自拍,高质量图片很多","资源不多,更新慢"],
            "x-art.com":["质量很高,真的很高","全部收费,屌比请绕过"]
        },
        "日韩":{
            "tokyo-hot":["质量怎样不清楚,个人已经不喜欢日韩范了","听说是收费的"]
        },
        "大陆":{
            "1024":["全部免费,真好,好人一生平安","服务器在国外,慢"]
        }
    }
    av_catalog["大陆"]["1024"][1] = "可以在国内做镜像"
    
    av_catalog.setdefault("taiwan",{"www.baidu.com":[1,2]})
    print(av_catalog)
    '''
    info = {
        'stu1101': "TengLan Wu",
        'stu1102': "LongZe Luola",
        'stu1103': "XiaoZe Maliya",
    }
    
    for i in info:
        print(i,info[i])
    
    for k,v in info.items():
        print(k,v)
    # b = {
    #     'stu1101':"Alex",
    #     1:3,
    #     2:5
    # }
    # info.update(b)
    # print(info)
    # c = dict.fromkeys([6,7,8],[1,{"name":"alex"},444])
    # print(c)
    # c[7][1]['name'] = "Jack Chen" #共用一个内存
    # print(c)
    # print(info.items())
    
    
    # print(info)
    # # print(info["stu1101"])
    # print(info.get('stu1103'))
    #
    # print('stu1103' in info) #info.has_key("1103") in py2.x
    # info["stu1101"] = "武藤兰"
    # info["stu1104"] = "CangJingkong"
    
    #del
    # del info["stu1101"]
    # info.pop("stu1101")
    # info.popitem()
    # print(info)

    十、三级菜单

    #!/usr/bin/env python
    # -*- coding:utf-8 -*-
    data = {
        '北京':{
            "昌平":{
                "沙河":["oldboy","test"],
                "天通苑":["链家地产","我爱我家"]
            },
            "朝阳":{
                "望京":["奔驰","陌陌"],
                "国贸":{"CICC","HP"},
                "东直门":{"Avent","飞信"},
            },
            "海淀":{},
        },
        '山东':{
            "德州":{},
            "青岛":{},
            "济南":{}
        },
        '广东':{
            "东莞":{},
            "常熟":{},
            "佛山":{},
        },
    }
    exit_flag = False
    
    while not exit_flag:
        for i in data:
            print(i)
        choice = input("选择进入1>>:")
        if choice in data:
            while not exit_flag:
                for i2 in data[choice]:
                    print("	",i2)
                choice2 = input("选择进入2>>:")
                if choice2 in data[choice]:
                    while not exit_flag:
                        for i3 in data[choice][choice2]:
                            print("	", i3)
                        choice3 = input("选择进入3>>:")
                        if choice3 in data[choice][choice2]:
                            for i4 in data[choice][choice2][choice3]:
                                print("		",i4)
                            choice4 = input("最后一层,按b返回>>:")
                            if choice4 == "b":
                                pass
                            elif choice4 == "q":
                                exit_flag = True
                        if choice3 == "b":
                             break
                        elif choice3 == "q":
                            exit_flag = True
                if choice2 == "b":
                    break
                elif choice2 == "q":
                    exit_flag = True

    十一、作业

    购物车
    用户入口:
    1、商品信息存在文件里
    2、已购商品,余额记录

    商家入口:
    2、可以添加商品,修改商品价格

    #!/usr/bin/env python
    # -*- coding:utf-8 -*-
    # 用户或者是商家
    # 用户-登陆信息-卡里剩多少钱-打开商品列表-选择商品-打印已购商品,余额记录
    # 商家-登陆信息-添加商品/修改商品价格-存入文件
    user_info = {"zhangsan":[333333,30000],"lisi":[444444,40000],"wangwu":[555555,50000]}
    shopper_info = {"hhh":666666}
    user = input("user:")
    password = input("password:")
    shopping_list = []
    product_list = open("product_list.txt").readlines()
    if user in user_info and int(user_info[user][0]) == int(password):
        salary = int(user_info[user][1])
        print("Welcome %s to our shopping center!Your salary is %s" % (user, salary))
        while True:
            for k, v in enumerate(product_list):
                print(k, v)
            choice = input("Which product do you want to select?")
            shopping_list.append(product_list[int(choice)])
            shop_price = int(product_list[int(choice)].split(":")[1])
            salary -= shop_price
            print("Your shopping_list is %s and your salary is %s" % (shopping_list, salary))
            choice2 = input("Do you want to continue to shopping?")
            if choice2 == "n":
                print("Welcome to you next time!Your shopping_list is %s and your salary is %s" % (shopping_list, salary))
                break
            elif choice2 == "y":
                pass
    elif user in shopper_info and int(shopper_info[user]) == int(password):
        while True:
            print("1 add product
    ""2 modify price")
            choice3 = input("What do you want to do?")
            if choice3 == "1":
                product = input("Which product do you want to add?")
                price = input("This product's price is?")
                product_info = "
    "+product+":"+price
                with open("product_list.txt",'a+') as f:
                    f.write(product_info+'
    ')
                choice4 = input("Do you want to continue?")
                if choice4 == "y":
                    pass
                elif choice4 == "n":
                    break
            elif choice3 == "2":
                for k, v in enumerate(product_list):
                    print(k, v)
                choice5 = input("Which product do you want to modify?")
                new_price = input("This product's price is modify to?")
                old_price = product_list[int(choice5)].split(":")[1]
                file_data = ""
                with open("product_list.txt","r") as f:
                    for line in f:
                        if old_price in line:
                            line = line.replace(old_price,new_price) + '
    '
                        file_data += line
                with open("product_list.txt","w") as f:
                        f.write(file_data)
                choice6 = input("Do you want to continue?")
                if choice6 == "y":
                    pass
                elif choice6 == "n":
                    break
  • 相关阅读:
    UITableView 排序、删除
    iOS中arc的设置
    dynamics ax 2009 distinct实现及数组集合
    将关系数据库映射到业务实体
    常见负载均衡实现
    ibatis经验
    百度贴吧10亿量级LAMP架构分享
    dynamics ax 2009 字段类似的表绑定界面注意
    [转]大型动态应用系统框架
    .net 发展历程
  • 原文地址:https://www.cnblogs.com/guantou1992/p/11193381.html
Copyright © 2011-2022 走看看