码迷,mamicode.com
首页 > 编程语言 > 详细

Python入门篇(四)之字符串、字典、集合

时间:2018-03-05 18:17:24      阅读:256      评论:0      收藏:0      [点我收藏+]

标签:Python   字典   

1、字符串操作

字符串是无法修改的,只能作为查询.
在python中,加了引号的字符就是字符串类型,python并没有字符类型。
定义:name=‘kim‘ #name=str(‘kim‘)
用于标识:描述性的内容,如姓名,性别,国籍,种族
那单引号、双引号、多引号有什么区别呢? 让我大声告诉你,单双引号木有任何区别,只有下面这种情况 你需要考虑单双的配合
msg = "My name is Kim , I‘m 18 years old!"

多引号什么作用呢?作用就是多行字符串必须用多引号
msg = ‘‘‘<br/>今天我想写首小诗,<br/>歌颂我的同桌,<br/>你看他那乌黑的短发,<br/>好像一只炸毛鸡。<br/>‘‘‘ <br/>print(msg)

#!/usr/bin/python
# _*_ coding:utf-8 _*_
# Aothr: Kim
name = ‘my name is {name} and i am {years} old‘
print(name.capitalize()) #首字母大写  
==>执行结果:My name is {name} and i am {years} old

print(name.count("a")) #统计字母a的个数
=>执行结果:5

print(name.center(50,"-")) #统计50个字符,不够以-凑足,美观打印
=>执行结果:------my name is {name} and i am {years} old------

print(name.endswith("x")) #判断字符串是否以什么结尾,比如判断邮件地址是否以.com结尾,返回布尔值
=>执行结果:False

print(name.expandtabs(tabsize=30)) #tab键转换成多少个空格
=>执行结果:

print(name.find("name")) #查找字符返回的是索引,name在my name....(m-->0,y-->1......)
=>执行结果:3

print(name[name.find("y"):]) #字符串切片,打印y到最后
=>执行结果:y name is {name} and i am {years} old

print(name.format(name=‘alex‘,years=‘23‘)) #格式
=>执行结果:my name is alex and i am 23 old

print(name.format_map( {‘name‘:‘alex‘,‘years‘:12} )) #嵌入字典
=>执行结果:my name is alex and i am 23 old

print(name.index("and")) #取索引
=>执行结果:18

print(‘ab123‘.isalnum()) #判断是否是阿拉伯数字
=>执行结果:True

print(‘abA‘.isalpha())
=>执行结果:True

print(‘1.22‘.isdecimal()) #判断十进制
=>执行结果:False

print(‘1A‘.isdigit()) #判断是否数字
=>执行结果:False

print(‘222‘.isidentifier()) #判断是不是一个合法的标识符,或者是否是一个合法的变量
=>执行结果:False

print(‘a‘.islower()) #判断是否小写
=>执行结果:True

print(‘2AAA‘.isupper() #判断是否大写
=>执行结果:False

print(‘+‘.join( [‘1‘,‘2‘,‘3‘]) )
=>执行结果:1+2+3

print( name.ljust(50,‘*‘) ) #统计50个字符,不够用*在右侧凑足
=>执行结果:my name is {name} and i am {years} old************

print( name.rjust(50,‘-‘) ) #统计50个字符,不够用-在左侧凑足
=>执行结果:------------my name is {name} and i am {years} old

print(‘Alex‘.lower()) #大写变小写
=>执行结果:alex

print(‘Alex‘.upper()) #小写变大写
=>执行结果:ALEX

print(‘\nAlex‘.lstrip()) #去掉左边换行符
=>执行结果:Alex

print(‘Alex\n‘.rstrip()) #去掉右边换行符
=>执行结果:Alex

print(‘     Alex\n‘.strip()) #去掉换行和空格符
=>执行结果:Alex

p = str.maketrans("abcdef","123456") #类似加密,需要对齐(a-->1,b-->2,c-->3,以此类推)
print("alex li".translate(p))  
=>执行结果:1l5x li

print(‘alex li‘.replace(‘l‘,‘L‘,1)) #替换
=>执行结果:aLex li

print(‘alex li‘.rfind(‘l‘)) #找到最右边的值,返回下标
=>执行结果:5

print(‘al ex lil‘.split(‘l‘)) #以l作为分隔符
=>执行结果:[‘a‘, ‘ ex ‘, ‘i‘, ‘‘]

print(‘1+2+3+4‘.split(‘\n‘)) #以换行符分隔
=>执行结果:[‘1+2+3+4‘]

print(‘1+2\n+3+4‘.splitlines()) #识别换行符分隔
=>执行结果:[‘1+2‘, ‘+3+4‘]

print(‘Alex Li‘.swapcase()) #大写变小写,小写变大写
=>执行结果:aLEX lI

print(‘alex li‘.title()) #变成主题
=>执行结果:Alex Li

print(‘alex li‘.zfill(50)) #没啥卵用
=>执行结果:0000000000000000000000000000000000000000000alex li

2、字典操作

字典是一种key-value的数据类型,使用就想我们上学使用的字典,通过笔画、字母来差对应页的详细内容。字典可以嵌套列表
在{}内用逗号分隔,可以存放多个key:value的值,value可以是任意类型
定义:
info={‘name‘:‘egon‘,‘age‘:18,‘sex‘:18}
info=dict({‘name‘:‘egon‘,‘age‘:18,‘sex‘:18})
用于标识:存储多个值的情况,每个值都有唯一一个对应的key,可以更为方便高效地取值

2.1、语法:

info = {
    ‘stu1101‘:"Zhang san"
    ‘stu1102‘:"Li si"
    ‘stu1103‘:"Wang wu"
}
print(info)
print(info["stu1101"]) #取值

执行结果:
{‘stu1102‘: ‘Li si‘, ‘stu1103‘: ‘Wang wu‘, ‘stu1101‘: ‘Zhang san‘}
Zhang san

2.2、字典的特性:

(1)dict是无序的,因为字典没有下标,也不需要下标。
(2)key必须是唯一的,so,天生去重

字典如下:
info = {
    ‘stu1101‘:"Zhang san"
    ‘stu1102‘:"Li si"
    ‘stu1103‘:"Wang wu"
}

2.3、字典的操作

(1)增加

info[‘stu1104‘] = "KIM"
print(info)
执行结果:
{‘stu1101‘: ‘Zhang san‘, ‘stu1104‘: ‘KIM‘, ‘stu1103‘: ‘Wang wu‘, ‘stu1102‘: ‘Li si‘}

(2)修改

info[‘stu1101‘] = "Grace"
print(info)
执行结果:
{‘stu1102‘: ‘Li si‘, ‘stu1103‘: ‘Wang wu‘, ‘stu1104‘: ‘KIM‘, ‘stu1101‘: ‘Grace‘}

(3)删除

del info["stu1101"]
info.pop("stu1101") #标准删除姿势
info.popitem() #随机删除
print(info)
执行结果:
{‘stu1103‘: ‘Wang wu‘, ‘stu1102‘: ‘Li si‘}

(4)查找

print("stu1102" in info) #查找stu1102是否在info字典中
执行结果:True

print(info.get("stu1101")) #获取
print(info["stu1101"]) #和get方法是一样的,但是如果key不存在,就会报错,get不会,不存在只会返回none
执行结果:
Zhang san
Zhang san

print(info.get(‘stu1106‘))
执行结果:None
print(info["stu1106"])
执行结果:KeyError: ‘stu1106‘

(5)多级字典嵌套及操作

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‘: [‘全部免费,真好,好人一生平安‘, ‘北京欢迎你‘]}, ‘欧美‘: {‘letmedothistoyou.com‘: [‘多是自拍,高质量图片很多‘, ‘资源不多,更新慢‘], ‘x-art.com‘: [‘质量很高,真的很高‘, ‘全部收费,屌比请绕过‘], ‘www.pornhub.com‘: [‘很多免费的,也很大‘, ‘质量比yourporn高点‘], ‘www.youporn.com‘: [‘很多免费的,世界最大的‘, ‘质量一般‘]}, ‘日韩‘: {‘tokyo-hot‘: [‘质量怎样不清楚,个人已经不喜欢日韩范了‘, ‘听说是收费的‘]}}

av_catalog["大陆"]["1024"][1] += ",可以使用爬虫" #增加内容
print(av_catalog["大陆"]["1024"]) #只打印大陆--1024内容
执行结果:
[‘全部免费,真好,好人一生平安‘, ‘北京欢迎你,可以使用爬虫‘]

(6)其他操作

info = {
    ‘stu1101‘:"Zhang san",
    ‘stu1102‘:"Li si",
    ‘stu1103‘:"Wang wu",
}

(1)values
print(info.values()) #打印所有的value
执行结果:dict_values([‘Li si‘, ‘Zhang san‘, ‘Wang wu‘])

(2)keys
print(info.keys()) #打印所有的key
执行结果:dict_keys([‘stu1103‘, ‘stu1102‘, ‘stu1101‘])

(3)setdefault 在字典中取值,如果能取到直接返回,如果无法取到值,则会进行创建增加。
info.setdefault("stu1106","Alex") #增加键值对
print(info)
执行结果:{‘stu1102‘: ‘Li si‘, ‘stu1103‘: ‘Wang wu‘, ‘stu1106‘: ‘Alex‘, ‘stu1101‘: ‘Zhang san‘}

info.setdefault("stu1102","Alex")
print(info)
执行结果:{‘stu1101‘: ‘Zhang san‘, ‘stu1102‘: ‘Li si‘, ‘stu1103‘: ‘Wang wu‘}

(4)update
info = {
    ‘stu1101‘:"Zhang san",
    ‘stu1102‘:"Li si",
    ‘stu1103‘:"Wang wu",
}
b = {
    "stu1104":"xiaoqiang",
    1:2,
    3:4
}
info.update(b) #将b字典合并到info字典中
print(info)
执行结果:{‘stu1103‘: ‘Wang wu‘, 3: 4, ‘stu1102‘: ‘Li si‘, 1: 2, ‘stu1101‘: ‘Zhang san‘, ‘stu1104‘: ‘xiaoqiang‘}

(5)items
print(info.items()) #打印出键值对
执行结果:
dict_items([(‘stu1102‘, ‘Li si‘), (‘stu1101‘, ‘Zhang san‘), (‘stu1103‘, ‘Wang wu‘)])

(7)循环字典dict

方法一:
info = {
    ‘stu1101‘:"Zhang san",
    ‘stu1102‘:"Li si",
    ‘stu1103‘:"Wang wu",
}
for i in info:
    print(i,info[i])
执行结果:
stu1101 Zhang san
stu1102 Li si
stu1103 Wang wu

方法二:
for k,v in info.items(): #会先把dict转成list,数据里大时莫用
    print(k,v)
执行结果:
stu1102 Li si
stu1103 Wang wu
stu1101 Zhang san    

2.4、程序练习

程序: 三级菜单

要求:

1.打印省、市、县三级菜单
2.可返回上一级
3.可随时退出程序
很low的程序,只是练习而已,别当真~!

#!/usr/bin/python
# _*_ coding:utf-8 _*_
# Aothr: Kim

info = {
    "广东省":{
        "中山市":{
            "东区":["威尼斯","行政中心"],
            "南区":["树木园","中澳花园"],
            "西区":["汽车站","剑桥郡"]},
        "广州市":{
            "天河区":["珠江新城","天河客运站"],
            "花都区":["培正学院","广州北站"],
        }
    },
    "福建省":{
        "厦门市":{
            "厦门":["鼓浪屿","厦门大学"]}
    },
    "湖南省":{
        "长沙市":{
            "长沙":["臭豆腐专卖店","凤凰古城"],}
    }
}
exit_flag = False #增加标志位

while True:
    for i in info:
        print(i)
    province = input("请输入你想要去的省份:")
    if province in info:
            while True:
                for i2 in info[province]:
                    print("\t", i2)
                city = input("如需返回请上级菜单请输入b,退出请按q,请选择地市:")
                if city in info[province]:
                    while True:
                        for i3 in info[province][city]:
                            print("\t\t", i3)
                        area = input("如需返回请上级菜单请输入b,退出请按q,请选择区域:")
                        if area in info[province][city]:
                            while True:
                                for i4 in info[province][city][area]:
                                    print(i4)
                                site = input("如需返回上级菜单请按b,退出请按q,请选择地点:")
                                if site in info[province][city][area]:
                                    print("正在为你选择合适路线......\n导航开始")
                                    back = input("最后一级菜单,可按b返回上一级菜单,退出请按q:")
                                    if back == "b":
                                        pass
                                    elif back == "q":
                                        exit()
                                elif site == ‘q‘:
                                    exit()
                                elif site == ‘b‘:
                                    break
                                else:
                                    print("你的输入错误,请重新输入:")
                        elif area == ‘q‘:
                            exit()
                        elif area == ‘b‘:
                            break
                        else:
                            print("你的输入错误,请重新输入:")
                elif city == ‘q‘:
                    exit()
                elif city == ‘b‘:
                    break
                else:
                    print("你的输入错误,请重新输入:")
    elif province == ‘q‘:
        exit()
    else:
        print("你的输入错误,请重新输入:")

购物车程序优化:
用户入口:
1、商品信息存在文件里
2、已购商品,余额记录
用户入口:
1、可以添加商品,修改商品价格

3、集合操作

集合是一个无序的,不重复的数据组合,它的主要作用如下:
去重,把一个列表变成集合,就自动去重了
关系测试,测试两组数据之前的交集、差集、并集等关系

3.1、集合去重功能

list_1 = [1,4,5,7,3,6,7,9] -->列表中有重复的值
list_1 = set(list_1)-->设置成集合
print(list_1,type(list_1)) -->去除了重复的7

执行结果:{1, 3, 4, 5, 6, 7, 9} <class ‘set‘>

3.2、关系测试

list_1 = [1,4,5,7,3,6,7,9]
list_1 = set(list_1)
list_2 =set([2,6,0,66,22,8,4])

#交集
print(list_1.intersection(list_2))
print(list_1 & list_2) -->符号表示法,使用“&”符号
执行结果:{4, 6}

#并集
print(list_1.union(list_2))
print(list_1 | list_2) -->符号表示法,使用“|”符号
执行结果:{0, 1, 2, 3, 4, 5, 6, 7, 66, 9, 8, 22}

#差集,in list_1 but not in list_2
print(list_1.difference(list_2))
print(list_2.difference(list_1))
print(list_1 - list_2) -->符号表示法,使用“-”符号
print(list_2 - list_1) 
执行结果:
{1, 3, 5, 9, 7}
{0, 8, 2, 66, 22}

#子集和父集
list_3=set([1,3,7])
print(list_3.issubset(list_1)) -->判断list_3是否为list_1的子集
print(list_1.issuperset(list_2)) -->判断list_1是否为list_2的父集
执行结果:True False

#对称差集
list_1 = set([1,4,5,7,3,6,7,9])
list_2 =set([2,6,0,66,22,8,4])
print(list_1.symmetric_difference(list_2)) -->相当于去重后的并集
print(list_1 ^ list_2) -->符号表示法,使用“^”符号
执行结果:{0, 1, 2, 66, 3, 5, 7, 8, 9, 22}

#判断集合是否有交集
list_3=set([1,3,7])
list_4 = set([5,6,8,7])
print(list_3.isdisjoint(list_4))
执行结果:True

3.3、基本操作

(1)添加一项

list_1 = set([1,4,5,7,3,6,7,9])
print(list_1.add(999))
执行结果:{1, 3, 4, 5, 6, 7, 999, 9}

(2)添加多项

print(list_1.update([888,777,555]))
执行结果:{1, 3, 4, 5, 6, 7, 9, 777, 555, 888}

(3)删除项,remove删除不存在的项时会报错,使用discard不会报错

list_1.remove(888) --->方法一
list_1.discard(888) --->方法二
print(list_1)
执行结果:{1, 3, 4, 5, 6, 7, 9, 777, 555}

list_1.remove(89999)
执行结果:KeyError: 89999

(4)随机删除

list_1 = set([{1, 3, 4, 5, 6, 7, 9, 777, 555, 888}])
print(list_1.pop()) #随机删除
print(list_1.pop())
print(list_1.pop())
执行结果:
1
3
4

(5)set的长度

list_1 = set([{1, 3, 4, 5, 6, 7, 9, 777, 555, 888}])
print(len(list_1))
执行结果:10

(6)判断x是否是s的成员

list_1 = set([{1, 3, 4, 5, 6, 7, 9, 777, 555, 888}])
print(666 in list_1) 
print(666 not in list_1)
执行结果:
False
True

(7)复制

list_1 = set([{1, 3, 4, 5, 6, 7, 9, 777, 555, 888}])
list_9 = list_1.copy()
print(list_9)
执行结果:{1, 3, 4, 5, 6, 7, 9, 777, 555, 888}

参考链接:金角大王

Python入门篇(四)之字符串、字典、集合

标签:Python   字典   

原文地址:http://blog.51cto.com/jinlong/2083149

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!