一、列表

列表是我们最以后最常用的数据类型之一,通过列表可以对数据实现最方便的存储、修改等操作

定义列表

names = ["ZhangYang", "Guyun", "Xiangpeng", "XuLiangChen"]

根据下标取值,下标从0开始

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

运行结果:
['ZhangYang', 'Guyun', 'Xiangpeng', 'XuLiangChen']
ZhangYang Xiangpeng

切片取值

print(names[1:3])   # 切片,取下标1和下标3之间的值,包括1但不包括3
print(names[3])   # 切片,取下标3的值
print(names[-2])   # 切片,取倒数第2个值
print(names[-2:])   # 切片,取列表最后2个值
print(names[0:3])   # 切片,取列表前3个值
print(names[:3])   # 切片,前边是0的,可以忽略

运行结果
['Guyun', 'Xiangpeng']
XuLiangChen
Xiangpeng
['Xiangpeng', 'XuLiangChen']
['ZhangYang', 'Guyun', 'Xiangpeng']
['ZhangYang', 'Guyun', 'Xiangpeng']

列表追加

names = ["ZhangYang", "Guyun", "Xiangpeng", "XuLiangChen"]
names.append("Leihaidong")      # 最后追加
print(names)

运行结果
['ZhangYang', 'Guyun', 'Xiangpeng', 'XuLiangChen', 'Leihaidong']

指定下标插入

names = ["ZhangYang", "Guyun", "Xiangpeng", "XuLiangChen"]
names.insert(1, "Chenronghua")      # 指定位置插入
names.insert(3, "Xinzhiyu")
print(names)

运行结果
['ZhangYang', 'Chenronghua', 'Guyun', 'Xinzhiyu', 'Xiangpeng', 'XuLiangChen']

替换列表值

names=['ZhangYang', 'Chenronghua', 'Guyun', 'Xinzhiyu', 'Xiangpeng', 'XuLiangChen']
names[2] = "Xiedi"      #指定下标替换

运行结果
['ZhangYang', 'Chenronghua', 'Xiedi', 'Xinzhiyu', 'Xiangpeng', 'XuLiangChen']

删除列表值

names=['ZhangYang', 'Chenronghua', 'Guyun', 'Xinzhiyu', 'Xiangpeng', 'XuLiangChen']
names.remove("Chenronghua")    #删除指定的内容
print(names)
运行结果
['ZhangYang', 'Guyun', 'Xinzhiyu', 'Xiangpeng', 'XuLiangChen']
names=['ZhangYang', 'Chenronghua', 'Guyun', 'Xinzhiyu', 'Xiangpeng', 'XuLiangChen']
del names[1]                #根据下标删除
print(names)
运行结果
['ZhangYang', 'Guyun', 'Xinzhiyu', 'Xiangpeng', 'XuLiangChen']
names=['ZhangYang', 'Chenronghua', 'Guyun', 'Xinzhiyu', 'Xiangpeng', 'XuLiangChen']
names.pop(1)                #删除最后一个
print(names)
运行结果
['ZhangYang', 'Guyun', 'Xinzhiyu', 'Xiangpeng', 'XuLiangChen']

查找元素位置

names=['ZhangYang', 'Chenronghua', 'Xiedi', 'Xinzhiyu', 'Xiangpeng', 'XuLiangChen']
print(names.index('Xiedi'))
运行结果:
2

统计重复的元素个数

names=['ZhangYang', 'Chenronghua', 'Xiedi', 'Xinzhiyu','Chenronghua', 'Xiangpeng', 'XuLiangChen']
print(names.count('Chenronghua'))
运行结果:
2

反转列表

names=['ZhangYang', 'Chenronghua', 'Xiedi', 'Xinzhiyu','Chenronghua', 'Xiangpeng', 'XuLiangChen']
print(names)
names.reverse()
print(names)
运行结果:
['ZhangYang', 'Chenronghua', 'Xiedi', 'Xinzhiyu', 'Chenronghua', 'Xiangpeng', 'XuLiangChen']
['XuLiangChen', 'Xiangpeng', 'Chenronghua', 'Xinzhiyu', 'Xiedi', 'Chenronghua', 'ZhangYang']

列表排序(默认按照ASCII码排序):

names = ["4ZhangYang", "#!Guyun", "Xiangpeng","Chenronghua", "XuLiangChen"]
names.sort()
print(names)
运行结果:
['#!Guyun', '4ZhangYang', 'Chenronghua', 'Xiangpeng', 'XuLiangChen']

列表扩展

names=['ZhangYang', 'Chenronghua', 'Xiedi', 'Xinzhiyu','Chenronghua', 'Xiangpeng', 'XuLiangChen']
names2=[1, 2, 3, 4]
names.extend(names2)
print(names)
运行结果:
['ZhangYang', 'Chenronghua', 'Xiedi', 'Xinzhiyu', 'Chenronghua', 'Xiangpeng', 'XuLiangChen', 1, 2, 3, 4]

删除列表

names2 = [1, 2, 3, 4]
del names2
print(names2)
运行结果:
Traceback (most recent call last):
  File "/Users/erick/PycharmProjects/oldboy_python/day2/names.py", line 45, in <module>
    print(names2)
NameError: name 'names2' is not defined

浅copy列表(只拷贝列表第一层的内存地址,当原列表第二层的元素发生改变时,新列表会跟着改变)


names = ["4ZhangYang", "#!Guyun", "xXiangpeng", ["alex", "jack"], "Chenronghua", "XuLiangChen"]
names2 = names.copy()
print(names)
print(names2)
names[2] = "向鹏"
print(names)
print(names2)
names[3][0] = "ALEXANDER"
print(names)
print(names2)
运行结果
['4ZhangYang', '#!Guyun', 'xXiangpeng', ['alex', 'jack'], 'Chenronghua', 'XuLiangChen']
['4ZhangYang', '#!Guyun', 'xXiangpeng', ['alex', 'jack'], 'Chenronghua', 'XuLiangChen']
['4ZhangYang', '#!Guyun', '向鹏', ['alex', 'jack'], 'Chenronghua', 'XuLiangChen']
['4ZhangYang', '#!Guyun', 'xXiangpeng', ['alex', 'jack'], 'Chenronghua', 'XuLiangChen']
['4ZhangYang', '#!Guyun', '向鹏', ['ALEXANDER', 'jack'], 'Chenronghua', 'XuLiangChen']
['4ZhangYang', '#!Guyun', 'xXiangpeng', ['ALEXANDER', 'jack'], 'Chenronghua', 'XuLiangChen']

深度copy(完全克隆)

import copy
names = ["4ZhangYang", "#!Guyun", "xXiangpeng", ["alex", "jack"], "Chenronghua", "XuLiangChen"]
# names2 = names.copy()
names2 = copy.deepcopy(names)
print(names)
print(names2)
names[2] = "向鹏"
print(names)
print(names2)
names[3][0] = "ALEXANDER"
print(names)
print(names2)
运行结果:
['4ZhangYang', '#!Guyun', 'xXiangpeng', ['alex', 'jack'], 'Chenronghua', 'XuLiangChen']
['4ZhangYang', '#!Guyun', 'xXiangpeng', ['alex', 'jack'], 'Chenronghua', 'XuLiangChen']
['4ZhangYang', '#!Guyun', '向鹏', ['alex', 'jack'], 'Chenronghua', 'XuLiangChen']
['4ZhangYang', '#!Guyun', 'xXiangpeng', ['alex', 'jack'], 'Chenronghua', 'XuLiangChen']
['4ZhangYang', '#!Guyun', '向鹏', ['ALEXANDER', 'jack'], 'Chenronghua', 'XuLiangChen']
['4ZhangYang', '#!Guyun', 'xXiangpeng', ['alex', 'jack'], 'Chenronghua', 'XuLiangChen']

浅copy三种方法
person=['name',['a',100]]
p1=copy.copy(person)
p2=person[:]
p3=list(person)

列表循环

names = ["4ZhangYang", "#!Guyun", "xXiangpeng", ["alex", "jack"], "Chenronghua", "XuLiangChen"]
for i in names:
    print(i)
运行结果:
4ZhangYang
#!Guyun
xXiangpeng
['alex', 'jack']
Chenronghua
XuLiangChen

二、元组

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

names = ("alex","jack","eric")

它只有2个方法,一个是count,一个是index

三、程序练习

购物车程序
需求:

  1. 启动程序后,让用户输入工资,然后打印商品列表
  2. 允许用户根据商品编号购买商品
  3. 用户选择商品后,检测余额是否够,够就直接扣款,不够就提醒
  4. 可随时退出,退出时,打印已购商品和余额
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 \033[31;1m%s\033[0m" %(p_item,salary))
                else:
                    print("\033[41;1m你的余额只剩[%s]啦,还买个毛线\033[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("your input error!")

四、字符串操作

name = "my name is alex"
print(name.capitalize())    # 首字母大写
print(name.count("a"))      # 统计指定字符的个数
print(name.center(50,"-"))  # 打印50个字符,不够的用"-"补充,name字符串居中
print(name.endswith("ex"))  # 判断字符串以什么结尾,匹配为True,不匹配为False

name = "my \tname is alex"
print(name.expandtabs(tabsize=30))  # 将\t转换成多长的空格
print(name.find("name"))            # 查找字符串位置
print(name[name.find("name"):9])    # 字符串切片

name = "my name is {name} and i am {year} old!"
print(name.format(name="alex", year=23))                # 传递参数内容
print(name.format_map({"name": "alex", "year": 23}))    # 用字典的方式传递参数
print("abc123".isalnum())       # 阿拉伯数字和阿拉伯英文字符,英文字符以及0-9数字
print("abA".isalpha())          # 是否为阿拉伯英文字符
print("10".isdecimal())         # 是否为十进制
print("1".isdigit())            # 是否为整数
print("addd_d".isidentifier())  # 是否为合法的标志符即变量名
print("aa".islower())           # 是否为小写
print("34234".isnumeric())      # 是否都为纯数字
print("My Name Is ".istitle())  # 判断是否为title,即每单词首字母大写
print("My Name Is ".isprintable())   # 判断能否打印,当是tty file或者drive file
print("My Name Is ".isupper())       # 判断是否全为大写
print("+".join(['1', '2', '3']))     # join成字符串
print(name.ljust(50, "*"))      # 左对齐,长度50个字符,并用*补齐
print(name.rjust(50, "-"))      # 右对齐,长度50个字符,并用-补齐
print("Alex".lower())           # 把大写变成小写
print("Alex".upper())           # 把小写变成大写
print("\n Alex".lstrip())       # 去除左侧的空格或回车
print("Alex \n".rstrip())       # 去除右侧的空格或回车
print("\n Alex \n".strip())     # 去除两侧的空格或回车
p = str.maketrans("abcdef", "123456")   # 字符对应替换
print("alex li".translate(p))
print("alex li".replace('l', 'L'))      # 替换指定字符
print("alex li".replace('l', 'L', 1))   # 替换1次
print("alex li".rfind('l'))             # 从左往右查找,返回最右侧的匹配字符的下标
print("al ex li".split())               # 切割,默认按照空格
print("al ex li".split('l'))            # 按照字符"l"切割
print("al \nex li".splitlines())        # 按照换行符\n切割
print("Alex Li".swapcase())             # 大写变小写,小写变大写
print("alex li".title())                # 变成title即每个单词的首字母大写
print("alex li".zfill(50))              # 长度50,不够用0左填充
运行结果:
My name is alex
2
-----------------my name is alex------------------
True
my                            name is alex
4
name 
my name is alex and i am 23 old!
my name is alex and i am 23 old!
True
True
True
True
True
True
True
True
True
False
1+2+3
my name is {name} and i am {year} old!************
------------my name is {name} and i am {year} old!
alex
ALEX
Alex
Alex
Alex
1l5x li
aLex Li
aLex li
5
['al', 'ex', 'li']
['a', ' ex ', 'i']
['al ', 'ex li']
aLEX lI
Alex Li
0000000000000000000000000000000000000000000alex li

五、字典

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

info = {
    'stu1101': "TengLan Wu",
    'stu1102': "LongZe Luola",
    'stu1103': "XiaoZe Maliya",
}
print(info)
print(info['stu1101'])
info["stu1101"] = "武藤兰"             # 修改
print(info)
info["stu1104"] = "Cangjingkong"       # 增加
print(info)
运行结果:
{'stu1101': 'TengLan Wu', 'stu1102': 'LongZe Luola', 'stu1103': 'XiaoZe Maliya'}
TengLan Wu
{'stu1101': '武藤兰', 'stu1102': 'LongZe Luola', 'stu1103': 'XiaoZe Maliya'}
{'stu1101': '武藤兰', 'stu1102': 'LongZe Luola', 'stu1103': 'XiaoZe Maliya', 'stu1104': 'Cangjingkong'}

删除

info = {
    'stu1101': "TengLan Wu",
    'stu1102': "LongZe Luola",
    'stu1103': "XiaoZe Maliya",
    'stu1104': 'Cangjingkong',
}
# del
# del info                               # 删除字典
del info['stu1101']                      # 删除元素
print(info)
info.pop("stu1102")                      # 删除元素
print(info)
info.popitem()                           # 随机删除一个
print(info)
运行结果:
{'stu1102': 'LongZe Luola', 'stu1103': 'XiaoZe Maliya', 'stu1104': 'Cangjingkong'}
{'stu1103': 'XiaoZe Maliya', 'stu1104': 'Cangjingkong'}
{'stu1103': 'XiaoZe Maliya'}

查找

info = {
    'stu1101': "TengLan Wu",
    'stu1102': "LongZe Luola",
    'stu1103': "XiaoZe Maliya",
}
# 查找
print(info.get('stu1103'))
运行结果:
XiaoZe Maliya

多级字典嵌套

av_catalog = {
    "欧美":{
        "www.youporn.com": ["很多免费的,世界最大的","质量一般"],
        "www.pornhub.com": ["很多免费的,也很大","质量比yourporn高点"],
        "letmedothistoyou.com": ["多是自拍,高质量图片很多","资源不多,更新慢"],
        "x-art.com":["质量很高,真的很高","全部收费,屌比请绕过"]
    },
    "日韩":{
        "tokyo-hot":["质量怎样不清楚,个人已经不喜欢日韩范了","听说是收费的"]
    },
    "大陆":{
        "1024":["全部免费,真好,好人一生平安","服务器在国外,慢"]
    }
}

av_catalog["大陆"]["1024"][1] = "可以在国内做镜像"
print(av_catalog["大陆"]["1024"])
运行结果:
['全部免费,真好,好人一生平安', '可以在国内做镜像']

打印keys和values

info = {
    'stu1101': "TengLan Wu",
    'stu1102': "LongZe Luola",
    'stu1103': "XiaoZe Maliya",
}
print(info.values())        # 打印key值
print(info.keys())          # 打印key
运行结果:
dict_values(['TengLan Wu', 'LongZe Luola', 'XiaoZe Maliya'])
dict_keys(['stu1101', 'stu1102', 'stu1103'])

setdefault

av_catalog = {
    "欧美":{
        "www.youporn.com": ["很多免费的,世界最大的","质量一般"],
        "www.pornhub.com": ["很多免费的,也很大","质量比yourporn高点"],
        "letmedothistoyou.com": ["多是自拍,高质量图片很多","资源不多,更新慢"],
        "x-art.com":["质量很高,真的很高","全部收费,屌比请绕过"]
    },
    "日韩":{
        "tokyo-hot":["质量怎样不清楚,个人已经不喜欢日韩范了","听说是收费的"]
    },
    "大陆":{
        "1024":["全部免费,真好,好人一生平安","服务器在国外,慢"]
    }
print(av_catalog.setdefault("台湾", {"www.baidu.com": [1, 2]}))   # 如果能取到就返回这个值,取不到就创建新的
print(av_catalog)
print(av_catalog.setdefault("大陆", {"www.baidu.com": [1, 2]}))
print(av_catalog)
运行结果:
{'www.baidu.com': [1, 2]}
{'欧美': {'www.youporn.com': ['很多免费的,世界最大的', '质量一般'], 'www.pornhub.com': ['很多免费的,也很大', '质量比yourporn高点'], 'letmedothistoyou.com': ['多是自拍,高质量图片很多', '资源不多,更新慢'], 'x-art.com': ['质量很高,真的很高', '全部收费,屌比请绕过']}, '日韩': {'tokyo-hot': ['质量怎样不清楚,个人已经不喜欢日韩范了', '听说是收费的']}, '大陆': {'1024': ['全部免费,真好,好人一生平安', '服务器在国外,慢']}, '台湾': {'www.baidu.com': [1, 2]}}
{'1024': ['全部免费,真好,好人一生平安', '服务器在国外,慢']}
{'欧美': {'www.youporn.com': ['很多免费的,世界最大的', '质量一般'], 'www.pornhub.com': ['很多免费的,也很大', '质量比yourporn高点'], 'letmedothistoyou.com': ['多是自拍,高质量图片很多', '资源不多,更新慢'], 'x-art.com': ['质量很高,真的很高', '全部收费,屌比请绕过']}, '日韩': {'tokyo-hot': ['质量怎样不清楚,个人已经不喜欢日韩范了', '听说是收费的']}, '大陆': {'1024': ['全部免费,真好,好人一生平安', '服务器在国外,慢']}, '台湾': {'www.baidu.com': [1, 2]}}

update

info = {
    'stu1101': "TengLan Wu",
    'stu1102': "LongZe Luola",
    'stu1103': "XiaoZe Maliya",
}

b = {
    'stu1101': "Alex",
    1: 3,
    2: 5
}
info.update(b)      # 两个字典合并,有交叉就更新,无交叉就创建
print(info)
运行结果:
{'stu1101': 'Alex', 'stu1102': 'LongZe Luola', 'stu1103': 'XiaoZe Maliya', 1: 3, 2: 5}

items

info = {
    'stu1101': "TengLan Wu",
    'stu1102': "LongZe Luola",
    'stu1103': "XiaoZe Maliya",
}
print(info.items()) # 将字典转换为列表
运行结果:
dict_items([('stu1101', 'TengLan Wu'), ('stu1102', 'LongZe Luola'), ('stu1103', 'XiaoZe Maliya')])

fromkeys

c = dict.fromkeys([6,7,8],"test")   # 初始化列表,参数列表为key,"test" 为默认key值
print(c)
运行结果:
{6: 'test', 7: 'test', 8: 'test'}

踩过的坑
d = dict.fromkeys([6,7,8],[1,{"name":"alex"},444])      # 注意多层,引用的是内存地址
print(d)
d[7][1]["name"] = "Jcak chen"
print(d)
运行结果:
{6: [1, {'name': 'alex'}, 444], 7: [1, {'name': 'alex'}, 444], 8: [1, {'name': 'alex'}, 444]}
{6: [1, {'name': 'Jcak chen'}, 444], 7: [1, {'name': 'Jcak chen'}, 444], 8: [1, {'name': 'Jcak chen'}, 444]}

循环字典

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返回上一级,q退出程序

data = {
    "北京": {
        "昌平":{
            "沙河":["oldboy", "test"],
            "天通苑":["链家地产", "我爱我家"]
        },
        "朝阳":{
            "望京":["奔驰", "陌陌"],
            "国贸":["CICC","HP"],
            "东直门":["Adevetn","飞信"]
        },
        "海淀":{

        },
    },
    "山东":{
        "德州":{},
        "青岛":{},
        "济南":{}
    },
    "广东":{
        "东莞":{},
        "常熟":{},
        "佛山":{}
    }
}

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("\t",i2)
            choice2 = input("选择进入2>>:")
            if choice2 in data[choice]:
                while not exit_flag:
                    for i3 in data[choice][choice2]:
                        print("\t\t",i3)
                    choice3 = input("请选择进入3>>:")
                    if choice3 in data[choice][choice2]:
                        for i4 in data[choice][choice2][choice3]:
                            print("\t\t",i4)
                        choice4 = input("选择进入4>>:")
                        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. 已购商品,余额记录

商家入口

  1. 可以添加商品
  2. 可以修改商品价格