Python中各种数据类型的操作

本节内容

  1. 列表、元组操作
  2. 字符串操作
  3. 字典操作
  4. 集合操作

1. 列表、元组操作

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

定义列表

1
names = ['Alex',"Tenglan",'Eric']
# 列表
name2 = ["shantianfang", "huojin", "jinyong", "eryuehe"]
print(name2)

# 循环显示元素
for i in name2:
print(i)

通过下标访问列表中的元素,下标从0开始计数

1
2
3
4
5
6
7
8
>>> names[0]
'Alex'
>>> names[2]
'Eric'
>>> names[-1]
'Eric'
>>> names[-2#还可以倒着取
'Tenglan'

切片:取多个元素  

# # 截取切片的使用,注意取值范围是左闭右开区间
# print(name2[1:3])
#
# # 从后向前取值,:前不能有负数
# print(name2[-1])
# print(name2[-3:-1])
#
# print(name2[:3])
# print(name2[0:3])

追加

# 追加
# name2.append("laoli")
# print(name2)

插入

# # 插入到huojin前
# name2.insert(1, "laozhang")
# print(name2)

修改

# # 修改掉huojin
# name2[2] = "zhangliao"
# print(name2)

删除

# 删除的方法一:
name2.remove("zhangliao")
# 删除的方法二:按列表的元素下标删除
# del name2[1]
# 删除列表:
# del name2

# 删除的方法三:默认从后往前删除最后一个
# name2.pop()
# 加入下标 name2.pop(1) 与 del name2[1] 同意
# name2.pop(1)
print(name2)

扩展

# 列表扩展
print(name2)
name3 = [1, 2, 3, 4]
name2.extend(name3)
print(name2,name3)

拷贝

 import copy  # 深Copy使用
name2 = ["4shantianfang", "#!huojin", "jinyong", "Eryuehe", "caocao"]# Copy列表
name4 = name2.copy()
print(name2)
print(name4)
# 修改列表,查看复制列表状态
name2[4] = "曹操"
print(name2)
print(name4)

====================================================================================================================================
name2 = ["4shantianfang", "#!huojin", ["tangseng", "wukong"], "jinyong", "Eryuehe", "caocao"]

# 深浅Copy列表
name4 = name2.copy()
print(name2)
print(name4)
# 修改列表中包含列表的元素,
name2[1] = "shaseng"
name2[2][1] = "zhubajie"
print(name2)
print(name4)

['4shantianfang', 'shaseng', ['tangseng', 'zhubajie'], 'jinyong', 'Eryuehe', 'caocao']
['4shantianfang', '#!huojin', ['tangseng', 'zhubajie'], 'jinyong', 'Eryuehe', 'caocao']


# 深浅Copy的原因和内存结构有关,这里的copy只是copy出列表中列表的内存地址,修改嵌套中的列表后直接按照地址找到斌修改


# 如果想完整的Copy出一份数据的如下操做
print("==" * 30)
name6 = copy.copy(name2)
print("name6:", name6)

# 深Copy
print("==" * 30)
name7 = copy.deepcopy(name2) # 深Copy
print("name7:", name7)

============================================================
name6: ['4shantianfang', 'shaseng', ['tangseng', 'zhubajie'], 'jinyong', 'Eryuehe', 'caocao']
============================================================
name7: ['4shantianfang', 'shaseng', ['tangseng', 'zhubajie'], 'jinyong', 'Eryuehe', 'caocao']



copy真的这么简单么?那我还讲个屁。。。

 

# 清空列表
# print(name2.clear())
# print(name2)


 

统计

# # 统计元素
# print(name2.count("jinyong"))

排序&

name2 = ["4shantianfang", "#!huojin", "jinyong", "Eryuehe"]
# 排序命令
name2.sort()
print(name2)

 

翻转

# 反转命令
# name2.reverse()
# print(name2)

获取下标

 

元组

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

语法

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

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

程序练习 

请闭眼写出以下程序。

程序:购物车程序

需求:

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

 

2. 字符串操作   

特性:不可修改 

复制代码
name.capitalize()  首字母大写
name.casefold()   大写全部变小写
name.center(50,"-")  输出 '---------------------Alex Li----------------------'
name.count('lex') 统计 lex出现次数
name.encode()  将字符串编码成bytes格式
name.endswith("Li")  判断字符串是否以 Li结尾
 "Alex\tLi".expandtabs(10) 输出'Alex      Li', 将\t转换成多长的空格 
 name.find('A')  查找A,找到返回其索引, 找不到返回-1 

format :
    >>> msg = "my name is {}, and age is {}"
    >>> msg.format("alex",22)
    'my name is alex, and age is 22'
    >>> msg = "my name is {1}, and age is {0}"
    >>> msg.format("alex",22)
    'my name is 22, and age is alex'
    >>> msg = "my name is {name}, and age is {age}"
    >>> msg.format(age=22,name="ale")
    'my name is ale, and age is 22'
format_map
    >>> msg.format_map({'name':'alex','age':22})
    'my name is alex, and age is 22'


msg.index('a')  返回a所在字符串的索引
'9aA'.isalnum()   True

'9'.isdigit() 是否整数
name.isnumeric  
name.isprintable
name.isspace
name.istitle
name.isupper
 "|".join(['alex','jack','rain'])
'alex|jack|rain'


maketrans
    >>> intab = "aeiou"  #This is the string having actual characters. 
    >>> outtab = "12345" #This is the string having corresponding mapping character
    >>> trantab = str.maketrans(intab, outtab)
    >>> 
    >>> str = "this is string example....wow!!!"
    >>> str.translate(trantab)
    'th3s 3s str3ng 2x1mpl2....w4w!!!'

 msg.partition('is')   输出 ('my name ', 'is', ' {name}, and age is {age}') 

 >>> "alex li, chinese name is lijie".replace("li","LI",1)
     'alex LI, chinese name is lijie'

 msg.swapcase 大小写互换


 >>> msg.zfill(40)
'00000my name is {name}, and age is {age}'



>>> n4.ljust(40,"-")
'Hello 2orld-----------------------------'
>>> n4.rjust(40,"-")
'-----------------------------Hello 2orld'


>>> b="ddefdsdff_哈哈" 
>>> b.isidentifier() #检测一段字符串可否被当作标志符,即是否符合变量命名规则
True

3. 字典操作

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

语法:

# 字典操作:
# 特点:key-value的数据类型,唯一,无序的
info = {
'stu1101': "Liang Xu",
'stu1102': "YunRui Bai",
'stu1103': "Ping Jiang",
}

字典的特性:

  • dict是无序的
  • key必须是唯一的,so 天生去重

增加

info["stu1104"] = "徐庆"
#不存在就创建

修改

# 存在的话就修改
info["stu1101"] = "徐良"

删除

# 删除功能:删除指定字符
# del info["stu1101"]
# info.pop("stu1104")

# 随机删除,我的是最后一个
# info.popitem()

查找

# 查找方法一:确定存在用下面,若存在返回,若不存在报错
# info["stu1104"]
# 查找方法二:存在就返回,不存在就是None
# print(info.get('stu1104'))
# 查找方法三:在就返回True,不在就返回False
# print('stu1101' in info)

多级字典嵌套及操作

xiaoshuo = {
"shantianfang": {
"baimeidaxia": ["xuliang", "baiyunrui"],
"sanxiajian": ["shengying", "zhugeyuanying"],
"suitangyanyi": ["qinqiong", "shanxiongxin"],
},
"jinyong": {
"tianlongbabu": ["xiaofeng", "xuzhu", "duanyu"]
},
"eryuehe": {
"1024": ["康熙王朝", "雍正王朝"]
}
}

# 修改指定位置的字符
# xiaoshuo["eryuehe"]["1024"][1] = "乾隆王朝"
# 修改追加指定位置的字符
# xiaoshuo["eryuehe"]["1024"][1] += ",乾隆王朝"
# print(xiaoshuo["eryuehe"]["1024"])


print(xiaoshuo)

其它姿势

# 获取字典的值
# print(info.values())
#dict_values(['Liang Xu', 'YunRui Bai', 'Ping Jiang'])

# 获取字典的键
print(info.keys())
dict_keys(['stu1101', 'stu1102', 'stu1103'])
# 没有匹配的创建一个新的值,有的话就返回
# xiaoshuo.setdefault("huojin", {"34": ["shijianjianshi"]})
# xiaoshuo.setdefault("eryuehe", {"34": ["shijianjianshi"]})

# 字典更新,有则改之无则加之
info1 = {1: 2, 2: 3, "stu1105": "房书安", "stu1102": "笑天王白春"}
info.update(info1)
print(info)

{'stu1101': 'Liang Xu', 'stu1102': 'YunRui Bai', 'stu1103': 'Ping Jiang'}
{'stu1101': 'Liang Xu', 'stu1102': '笑天王白春', 'stu1103': 'Ping Jiang', 1: 2, 2: 3, 'stu1105': '房书安'}

# 把字典以列表形式遍历出来
print(info.items())
# 初始化一个新字典并附一个值
c = info.fromkeys([6, 7, 8], "test")
print(c)
print(info.items())
 

循环dict 

复制代码
#方法1比2较高效
for key in info:
    print(key,info[key])

#方法2
for k,v in info.items(): #会先把dict转成list,数据量大时候机器废了
    print(k,v)
复制代码

程序练习

程序: 三级菜单

要求: 

  1. 打印省、市、县三级菜单
  2. 可返回上一级
  3. 可随时退出程序

 

menu = {
    '北京':{
        '海淀':{
            '五道口':{
                'soho':{},
                '网易':{},
                'google':{}
            },
            '中关村':{
                '爱奇艺':{},
                '汽车之家':{},
                'youku':{},
            },
            '上地':{
                '百度':{},
            },
        },
        '昌平':{
            '沙河':{
                '老男孩':{},
                '北航':{},
            },
            '天通苑':{},
            '回龙观':{},
        },
        '朝阳':{},
        '东城':{},
    },
    '上海':{
        '闵行':{
            "人民广场":{
                '炸鸡店':{}
            }
        },
        '闸北':{
            '火车战':{
                '携程':{}
            }
        },
        '浦东':{},
    },
    '山东':{},
}



tag=True
while tag:
    menu1=menu
    for key in menu1: # 打印第一层
        print(key)

    choice1=input('第一层>>: ').strip() # 选择第一层

    if choice1 == 'b': # 输入b,则返回上一级
        break
    if choice1 == 'q': # 输入q,则退出整体
        tag=False
        continue
    if choice1 not in menu1: # 输入内容不在menu1内,则继续输入
        continue

    while tag:
        menu_2=menu1[choice1] # 拿到choice1对应的一层字典
        for key in menu_2:
            print(key)

        choice2 = input('第二层>>: ').strip()

        if choice2 == 'b':
            break
        if choice2 == 'q':
            tag = False
            continue
        if choice2 not in menu_2:
            continue

        while tag:
            menu_3=menu_2[choice2]
            for key in menu_3:
                print(key)

            choice3 = input('第三层>>: ').strip()
            if choice3 == 'b':
                break
            if choice3 == 'q':
                tag = False
                continue
            if choice3 not in menu_3:
                continue

            while tag:
                menu_4=menu_3[choice3]
                for key in menu_4:
                    print(key)

                choice4 = input('第四层>>: ').strip()
                if choice4 == 'b':
                    break
                if choice4 == 'q':
                    tag = False
                    continue
                if choice4 not in menu_4:
                    continue

                # 第四层内没数据了,无需进入下一层

 

menu = {
    '北京':{
        '海淀':{
            '五道口':{
                'soho':{},
                '网易':{},
                'google':{}
            },
            '中关村':{
                '爱奇艺':{},
                '汽车之家':{},
                'youku':{},
            },
            '上地':{
                '百度':{},
            },
        },
        '昌平':{
            '沙河':{
                '老男孩':{},
                '北航':{},
            },
            '天通苑':{},
            '回龙观':{},
        },
        '朝阳':{},
        '东城':{},
    },
    '上海':{
        '闵行':{
            "人民广场":{
                '炸鸡店':{}
            }
        },
        '闸北':{
            '火车战':{
                '携程':{}
            }
        },
        '浦东':{},
    },
    '山东':{},
}



#part1(初步实现):能够一层一层进入
layers = [menu, ]

while True:
    current_layer = layers[-1]
    for key in current_layer:
        print(key)

    choice = input('>>: ').strip()

    if choice not in current_layer: continue

    layers.append(current_layer[choice])



#part2(改进):加上退出机制
layers=[menu,]

while True:
    if len(layers) == 0: break
    current_layer=layers[-1]
    for key in current_layer:
        print(key)

    choice=input('>>: ').strip()

    if choice == 'b':
        layers.pop(-1)
        continue
    if choice == 'q':break

    if choice not in current_layer:continue

    layers.append(current_layer[choice])
#作业二:请闭眼写出购物车程序
#需求:
用户名和密码存放于文件中,格式为:egon|egon123
启动程序后,先登录,登录成功则让用户输入工资,然后打印商品列表,失败则重新登录,超过三次则退出程序
允许用户根据商品编号购买商品
用户选择商品后,检测余额是否够,够就直接扣款,不够就提醒
可随时退出,退出时,打印已购买商品和余额
import os

product_list = [['Iphone7',5800],
                ['Coffee',30],
                ['疙瘩汤',10],
                ['Python Book',99],
                ['Bike',199],
                ['ViVo X9',2499],

                ]

shopping_cart={}
current_userinfo=[]

db_file=r'db.txt'

while True:
    print('''
    1 登陆
    2 注册
    3 购物
    ''')

    choice=input('>>: ').strip()

    if choice == '1':
        #1、登陆
        tag=True
        count=0
        while tag:
            if count == 3:
                print('\033[45m尝试次数过多,退出。。。\033[0m')
                break
            uname = input('用户名:').strip()
            pwd = input('密码:').strip()

            with open(db_file,'r',encoding='utf-8') as f:
                for line in f:
                    line=line.strip('\n')
                    user_info=line.split(',')

                    uname_of_db=user_info[0]
                    pwd_of_db=user_info[1]
                    balance_of_db=int(user_info[2])

                    if uname == uname_of_db and pwd == pwd_of_db:
                        print('\033[48m登陆成功\033[0m')

                        # 登陆成功则将用户名和余额添加到列表
                        current_userinfo=[uname_of_db,balance_of_db]
                        print('用户信息为:',current_userinfo)
                        tag=False
                        break
                else:
                    print('\033[47m用户名或密码错误\033[0m')
                    count+=1

    elif choice == '2':
        uname=input('请输入用户名:').strip()
        while True:
            pwd1=input('请输入密码:').strip()
            pwd2=input('再次确认密码:').strip()
            if pwd2 == pwd1:
                break
            else:
                print('\033[39m两次输入密码不一致,请重新输入!!!\033[0m')

        balance=input('请输入充值金额:').strip()

        with open(db_file,'a',encoding='utf-8') as f:
            f.write('%s,%s,%s\n' %(uname,pwd1,balance))

    elif choice == '3':
        if len(current_userinfo) == 0:
            print('\033[49m请先登陆...\033[0m')
        else:
            #登陆成功后,开始购物
            uname_of_db=current_userinfo[0]
            balance_of_db=current_userinfo[1]

            print('尊敬的用户[%s] 您的余额为[%s],祝您购物愉快' %(
                uname_of_db,
                balance_of_db
            ))

            tag=True
            while tag:
                for index,product in enumerate(product_list):
                    print(index,product)
                choice=input('输入商品编号购物,输入q退出>>: ').strip()
                if choice.isdigit():
                    choice=int(choice)
                    if choice < 0 or choice >= len(product_list):continue

                    pname=product_list[choice][0]
                    pprice=product_list[choice][1]
                    if balance_of_db > pprice:
                        if pname in shopping_cart: # 原来已经购买过
                            shopping_cart[pname]['count']+=1
                        else:
                            shopping_cart[pname]={'pprice':pprice,'count':1}

                        balance_of_db-=pprice # 扣钱
                        current_userinfo[1]=balance_of_db # 更新用户余额
                        print("Added product " + pname + " into shopping cart,\033[42;1myour current\033[0m balance " + str(balance_of_db))

                    else:
                        print("买不起,穷逼! 产品价格是{price},你还差{lack_price}".format(
                            price=pprice,
                            lack_price=(pprice - balance_of_db)
                        ))
                    print(shopping_cart)
                elif choice == 'q':
                    print("""
                    ---------------------------------已购买商品列表---------------------------------
                    id          商品                   数量             单价               总价
                    """)

                    total_cost=0
                    for i,key in enumerate(shopping_cart):
                        print('%22s%18s%18s%18s%18s' %(
                            i,
                            key,
                            shopping_cart[key]['count'],
                            shopping_cart[key]['pprice'],
                            shopping_cart[key]['pprice'] * shopping_cart[key]['count']
                        ))
                        total_cost+=shopping_cart[key]['pprice'] * shopping_cart[key]['count']

                    print("""
                    您的总花费为: %s
                    您的余额为: %s
                    ---------------------------------end---------------------------------
                    """ %(total_cost,balance_of_db))

                    while tag:
                        inp=input('确认购买(yes/no?)>>: ').strip()
                        if inp not in ['Y','N','y','n','yes','no']:continue
                        if inp in ['Y','y','yes']:
                            # 将余额写入文件

                            src_file=db_file
                            dst_file=r'%s.swap' %db_file
                            with open(src_file,'r',encoding='utf-8') as read_f,\
                                open(dst_file,'w',encoding='utf-8') as write_f:
                                for line in read_f:
                                    if line.startswith(uname_of_db):
                                        l=line.strip('\n').split(',')
                                        l[-1]=str(balance_of_db)
                                        line=','.join(l)+'\n'

                                    write_f.write(line)
                            os.remove(src_file)
                            os.rename(dst_file,src_file)

                            print('购买成功,请耐心等待发货')

                        shopping_cart={}
                        current_userinfo=[]
                        tag=False


                else:
                    print('输入非法')


    else:
        print('\033[33m非法操作\033[0m')

 

 

4.集合操作

集合是一个无序的,不重复的数据组合,它的主要作用如下:

  • 去重,把一个列表变成集合,就自动去重了
  • 关系测试,测试两组数据之前的交集、差集、并集等关系

常用操作


# 集合的去重,将列表转换成集合
list_1 = [1, 2, 3, 4, 5, 6, 1, 2, 3, 4, 5, 6, 0]
# 将列表类型换行成集合类型
list_1 = set(list_1)
print(type(list_1), list_1)
# 交集方式一:
# list_3 = list_1.intersection(list_2)
# 交集方式二:
list_3 = list_1 & list_2
print(list_3)

# 对称差集方式一:
print(list_1.symmetric_difference(list_2))
# 对称差集方式二:
print(list_1 ^ list_2)


# Return True if two sets have a null intersection.
# 如果两个集合的交集为空,则返回True。
print(list_1.isdisjoint(list_2))

# 并集方式一:
# list_4 = list_1.union(list_2)
# 并集方式二:
list_4 = list_1 | list_2
print(list_4)

# 差集方式一:in list_1 but not in list_2 只在1里不在2里的
print(list_1.difference(list_2))
# print(list_2.difference(list_1))
# 差集方式二:
print(list_1 - list_2)
 
# 子集
list_6 = set([2, 3, 4])
print(list_6.issubset(list_2))

返回True

# 父集
print(list_6.issuperset(list_2))

返回False

# 集合的基本操作:
# 添加一项
# list_1.add(999)
# print(list_1)

# 添加多项
list_1.update([100, 200, 300])
print(list_1)

# 删除动作:remove
# print(list_1.remove("eee"))

list_1.discard("1")
print(list_1.pop())
print(list_1)

 

声明:本文整理借鉴金角大王的Python之路,Day2 - Python基础2,仅供本人学习使用!!!

posted @ 2018-12-23 14:19  思江  阅读(312)  评论(0编辑  收藏  举报