Python笔记(二):数据类型及列表小程序

二、Python笔记2

本节主要记录了:数据类型的种类列表的切片字符串的操作以及字典的使用,并写了一个简单的购物车小程序。


数据类型

Python中有五个标准的数据类型:
- Numbers(数字)
- String(字符串)
- List(列表)
- Tuple(元组)
- Sets(集合)
- Dictionary(字典)
其中,列表元组、以及字典属于集合类型。

不可变数据类型(四个):Number(数字)、String(字符串)、Tuple(元组)、Sets(集合);
可变数据(两个):List(列表)、Dictionary(字典)

Numbers(数字)

数字类型用于存储数值,是不可改变的数据类型。
有四种不同的数字类型:
- int (有符号整型)
- float (浮点型)
- bool (布尔型)
- complex (复数)
Python 3 中没有长整型,整数类型均可用int来表示;

a = 10
b = 1.5
c = True
d = 2+3j
print(type(a), type(b), type(c), type(d))

数据类型

Python中常用的数值运算:
- +: 加法
- -: 减法
- *: 乘法
- /: 除法
- //: 除法(结果取整数)
- %: 取余
- **: 乘方

String(字符串)

  • python中字符串使用单引号(”)或双引号(”“)括起来,使用反斜杠(\)转义特殊字符。
  • 字符串的截取方法:变量[头下标:尾下标]
  • 索引值从0开始,-1位末尾开始的位置
  • 加号(+)可连接字符串,星号(*)可复制当前字符串。

字符串不可修改,即使做出的修改,也是覆盖掉了原字符串的修改;

列表使用举例

list = ["abc","def","ghi","jkl","mno","pqr","stu"]
print(list)           #直接输出该列表
print(list[0],list[3])             #选择列表某位输出
print(list[1:3])             #(切片) 输出第2个到第3个(顾头不顾尾)
print(list[-1])       #在不知道列表多少的情况下,直接取最后一个
print(list[-2:-1])      #由于顾头不顾尾,故这样取不到最后一个值
print(list[-2:])     #取最后两个
print(list[:3])      #取值若从第一位开始取,则开头0可以省略

#末尾追加
list.append("ZZZ")         #在列表末尾添加
print(list)

#插入追加
list.insert(1,"WWW")       #插入追加 要插入什么位置就写什么位置
print(list)

#替换相关位
list[2] = "DDD"       #直接替换相关位
print(list)

#删除相关位
list.remove("abc")       #1 直接写想要删除的内容
del list[0]              #2 删除该位置的内容
list.pop(0)              #3 效果与2相同

#查找相关内容的位置
print(list.index("def"))   #通过list.index("def")找到"def"所在位置

print(list[list.index("def")])         #找到位置,再打印该位置的内容

#查重
print(list.count("abc"))     #统计列表中有多少个abc

list.clear()              #清空
list.reverse()            #翻转列表
list.sort()        #排序,(按ASCII码)规则排序

#列表的合并
list.extend(list2)       #将另一个名为list2的列表合并进list列表的末尾

关于列表的复制:
一、直接 list2 = list

list = ["A","B","C",["D","d"],"E"]
list2 = list

list[2] = "菜"
list2[3][0] = "DIDI"

print(list)
print(list2)
#其中的两个列表完全指向同一地址,所以一变都变

输出结果为:
["A","B","菜",["DIDI","d"],"E"]
["A","B","菜",["DIDI","d"],"E"]

其中的两个列表完全指向同一地址,所以一变都变

二、使用 list.copy() 函数

list = ["A","B","C",["D","d"],"E"]
list2 = list.copy()

list[2] = "菜"
list2[3][0] = "DIDI"

print(list)
print(list2)

输出结果为:
["A","B","菜",["DIDI","d"],"E"]
["A","B","C",["DIDI","d"],"E"]

copy 仅为浅 copy,子列表在里面是一个单独的地址空间
copy 过来的也仅是内存地址的指针,指向子列表的内存
第一层的独立克隆了一份,第二层的仅 copy 的指针

三、使用 copy 库(深 copy )

import copy

list = ["A","B","C",["D","d"],"E"]
list2 = copy.deepcopy()

list[2] = "菜"
list2[3][0] = "DIDI"

print(list)
print(list2)

输出结果为:
["A","B","菜",["D","d"],"E"]
["A","B","C",["DIDI","d"],"E"]

字符串的常用操作

hello = "hello world!"

print(hello.capitalize())
>> Hello world!

print(hello.count("o"))        #字符串中有多少个o
>> 2

print(hello.center(50,"-"))      #一共打印50个字符,字符串放在中间,其余打印-
>> -------------------hello world!-------------------

print(hello.endswith("ld!"))       #判断是否以"ld!"结尾
>> True

list = "hello \tworld"        #加入\t(TAB键)

print(list.expandtabs(tabsize = 30))       #将字符串中的TAB键转成30个空格
>> hello                         world

print(hello.find("hello"))       #寻找hello的索引位置

#可用于字符串的切片,例如:
print(hello[hello.find("world"):])   #即可从world开始打印到末尾
>> world!

#format的使用:
introduce = "my name is {name} and I am {year} years old"
print(introduce.format(name = "Evan",year = "22"))
>> my name is Evan and I am 22 years old

#使用字典方法:
print(introduce.format_map({'name':'Evan','year':22}))
>>结果同上

isalnum:
print("ab33".isalnum())       #检测字符串是否仅包含字母和数字(不包括空格)
>> True

isidentifier:
print('1d'.isidentifier())      #判断是不是一个合法的标识符

istitle:
print('My name is...'.istitle())     #首字母是否大写

join:
print('+'.join(['1','2','3']))        #把+插入到1、2、3之间
>> 1+2+3

ljust:
print(hello.ljust(50,'*'))       #打印字符串,长度50,不够就用*补上
>> hello world!**************************************

rjust:   同上相反

lower/upper:    小写变大写/大写变小写

lstrip/rstrip:   去掉左边/右边回车(\n)

----------------
p = str.maketrans("abcdefgh","12345678")
print("aadef dh".translate(p))
>>11456 48

将 abcdefgh 和 12345678 一一对应,
然后将"aadef dh"转换为相对应的数字

----------------


replace:
print("aadef dh".replace("a","A"))
>>AAdef dh
print("aadef dh".replace("a","A",1))
>>Aadef dh                 #仅替换一个


split:
print("zz ww dd nb".split())
>>["zz","ww","dd","nb"]             #什么也没输入,相当于按空格分割字符串

字典

字典是一种key-value 的数据类型,可查找对应的内容
字典的特性
- dict 是无序的
- key 必须是唯一的

例:定义字典 info

#key-value

info = {
'stu1101':"zzzz",
'stu1102':"wwww",
'stu1103':"dddd",
}
print(info)

修改添加删除相应信息:

info["stu1101"] = "XXXX"   #修改
info["stu1104"] = "CCCC"        #添加

del info["stu1101"]
info.pop("stu1101")
info.popitem()    #随机删一个

查找

info["stu1101"]     #除非完全确定有该项,如果没有将报错,不建议使用;

print(info.get("stu1101"))    建议使用

更新

b = {
        "stu1101":"EEEE"
        "sru1204":"FFFF"
    }
info.update(b)
print(info)
>> "EEEE"将替换掉原 "stu1101" 的内容
>  "stu1204" 的内容将被添加进去

循环

for i in info:
    print(i,info[i])
#这样才能输出其中的所有内容

判断字典中是否有该内容

print("stu1101" in info)


多级字典的嵌套

log = {
    "一班":{
        "一组":["都是学神","占据考试榜首"]
    },
    "二班":{
        "种子组":["一班一组的强力竞争对手"],
        "清北组":["双子星阵容争夺学校排行榜首","榜首的另一有力争夺者"]
    },
    "三班":{
        "学而组":["三班的最强实力","但距榜首还有距离"]
    }
}   
  • 修改、替换
log["三班"]["学而组"][1] = "近来进步明显"  
>> 替换掉了"但距榜首还有距离"

key 尽量不要写中文

  • 增加(先查找,有就返回,没有就创建)
log.setdefault("四班",{"重点组":["新成立"]}
>> 首先将查找四班,如果有,则输出相应内容
>  没有则创建

——————————————————————–

程序练习

购物车小程序

学习了相关的列表的使用方法后,写一个小购物车程序练习一下

程序实现目标:

  • 首先请用户输入用来购物的金额总数
  • 然后打印商品列表,请用户输入商品序号选择商品
  • 选中商品加入购物车内,并从总金额中扣除商品价格
  • 输入 q 退出购买页面
  • 结束时打印购物车商品以及所剩下的金额

流程图

Created with Raphaël 2.1.2

程序实现

product_list = [
("Mac pro",9800),
("Iphone",5800),
("Bycle",2200),
("Rice cooker",1000),
("Bluetooth earphone",500),
("Book",200),
("Coffee",35)
]
shopping_list = []
salary = input("Please input your salary:")
if salary.isdigit():
    salary = int(salary)
    while True:
        for index,item in enumerate(product_list):
            print(index,item)
        user_choice = input("请输入您所需购买的商品序号:")
        if user_choice.isdigit():
            user_choice = int(user_choice)
            if user_choice >= 0 and user_choice < len(product_list):
                product = product_list[user_choice]
                if salary >= product[1]:
                    salary -= product[1]
                    shopping_list.append(product)
                    print("您的账户余额为\033[31;1m%s\033[0m"%salary)
                else:
                print("您当前的账户余额为\033[31;1m%s\033[0m,不足以支付当前商品价格,请重新选择!"%salary)
            else:
            print("您输入的商品序号\033[32;1m%s\033[0m不存在,请重新输入"%user_choice)
        elif user_choice == "q":
            print("-----------Your Shopping Cart----------")
            for i in shopping_list:
                print(i)
            print("您当前账户余额为\033[31;1m%s\033[0m ,感谢您的购物,再见!"%salary)
            exit()
        else:
            print("您的输入有误,请重新输入!")
else:
    print("Invalid Input!")

三级菜单

选择 省-> 市-> 县

list = {
    '山东':{
        "德州":{},
        "青岛":{},
        "济南":{}
    },
    '广东':{
        "东莞":{},
        "常熟":{},
        "佛山":{},
    },
    '河南':{
        "郑州":{},
        "洛阳":{
            "洛龙":["泉舜","市政府"],
            "西工":["王府井","建业"]
        }
    }
}
exit_flag = False
while not exit_flag:
    for i in list:
        print(i)
    choice = input("选择进入1>>:")
    if choice in list:
        while not exit_flag:
            for i2 in list[choice]:
                print("\t",i2)
            choice2 = input("选择进入2>>:")
            if choice2 in list[choice]:
                while not exit_flag:
                    for i3 in list[choice][choice2]:
                        print("\t\t",i3)            #两个TAB缩进
                    choice3 = input("选择进入3>>:")
                    if choice3 in list[choice][choice2]:
                        for i4 in list[choice][choice2][choice3]:
                            print("\t\t\t",i4)
                        choice4 = input("最后一层,按b返回>>:")
                        if choice4 == "b":
                            pass
                        elif choice4 == "q":
                            exit_flag = True
                    elif choice3 == "b":
                        break
                    elif choice3 == "q":
                        exit_flag = True
            elif choice2 == "b":
                    break
            elif choice2 == "q":
                exit_flag = True

猜你喜欢

转载自blog.csdn.net/weixin_42026630/article/details/80342502