三.python3 基础

数据类型

1.整数:整型int,长整型long(在python3中已经不区分了)

2.浮点型:float 带有小数位

3.字符串:string

字符串操作

重复打印

print("hello"*2)  #hellohello

切片

print("hello"[2:])  #llo

判断 in

a = "helle"
print("he" in a)   #True

格式字符串 %s

print("air is a men")         #air is a men
print("%s is a men"%"air")    #air is a men

字符串拼接  

.join() 可以将列表转换成字符串

a = "123"
b = "abc"
c = a+b
print(c)    #123abc    效率低
另一种方式: .join()
a = "123"
b = "abc"
c = "444"
d = "-----".join([a,b,c])  # d = "-----".join((a,b,c))
print(d)          #123-----abc-----444  

string,python内置的方法(python写好的方法):  

.count  统计字符串中某个元素的个数

a = "hello world"
b = a.count("l")
print(b)     #3

.capitalize() 首字母大写

a = "hello world"
b = a.capitalize()
print(b)     #Hello world

.center()      居中

a = "hello world"
b = a.center(50,"-")
print(b)     #-------------------hello world--------------------

.ljust()   左对齐

a = "hello world"
b = a.ljust(50,"-")
print(b)     #hello world---------------------------------------

.rjust()  右对齐

a = "hello world"
b = a.rjust(50,"-")
print(b)     #---------------------------------------hello world 

.endswith   以某个内容结尾的,返回布尔值

a = "hello world"
b = a.endswith("rld")
print(b)     #True

.startswith()   以某个内容结尾的,返回布尔值   会经常使用

a = "hello world"
b = a.startswith("he")
print(b)     #True

.expandtabs()    设置\t的空格缩进的个数,默认是4个空格

a = "he\tllo world"
b = a.expandtabs(tabsize=5)
print(b)     #he   llo world

.find()   从左至右,查找到第一个元素,并将索引值返回,当查找的字符串中没有要找的元素时,不会报错,会输出-1

a = "hello world"
b = a.find("o")
print(b)     #4

 

a = "hello world"
b = a.find("x")
print(b)     #-1 

.rfind()    从右至左,查找到第一个元素,并将索引值返回,当查找的字符串中没有要找的元素时,不会报错,会输出-1

a = "hello world"
b = a.rfind("o")
print(b)     #7 

.format()   格式化输出的另一种方式,以赋值的形式

a = "hello world {name}{age}"
print(a.format(name = "air",age = 37))     #hello world air37

.format_map()  格式化输出的另一种方式,以字典的形式

a = "hello world {name}{age}"
print(a.format_map({"name":"air","age":37}))    #hello world air37

.index()  从左至右,查找到第一个元素,并将索引值返回,等同于find,不同的是 当查找的字符串中没有要找的元素时,会报错。

a = "hello world"
b = a.index("o")
print(b)     #4

.rindex()       从右至左,查找到第一个元素,并将索引值返回,等同于find,不同的是 当查找的字符串中没有要找的元素时,会报错。

a = "hello world"
b = a.rindex("o")
print(b)     #7

.isalnum()   判断字符串是否包含了数字和字母,并返回布尔值

a = "123abc"
print(a.isalnum())   #True

.isdecimal()  判断字符串是否是一个十进制的数字,并返回布尔值

a = "2232"
print(a.isdecimal())   #True

.isdigit()  判断字符串是否是一个整型数字,并返回布尔值

a = "2232"
print(a.isdigit())    #True

.isalpha()   判断字符串是否是一个由纯字母组成的,并返回布尔值

a = "amv"
print(a.isalpha())   #True

.isnumeric()  判断字符串是否是一个整型数字,并返回布尔值,和digit相同

a = "2232"
print(a.isnumeric())    #True

.isidentifier()    检验变量是否使用了非法字符,并返回布尔值

a = "2232"
print(a.isnumeric())    #True

.islower()    判断字符串中的元素是否都是小写,并返回布尔值

a = "aaad"
print(a.islower())   #True

.isupper() 判断字符串中的元素是否都是大写,并返回布尔值

a = "AAAD"
print(a.isupper())   #True

.isspace()  判断字符串中的元素是否都是空格,并返回布尔值

print("  ".isspace())  #True

.istitle()  判断字符串中的每一个单词的首字母是否为大写,并且其他的都是小写,并返回布尔值

a = "My Name Is 111"
print(a.istitle())    #True

a = "My Name IS 111"
print(a.istitle())    #False

.isprintable()   判断字符串是否是可打印的,并返回布尔值

a = "11"
print(a.isprintable())  #True

.lower()  将字符串内的所有字母变成小写

a = "AA1"
print(a.lower())   #aa1

.upper()  将字符串内的所有字母变成大写

a = "aa1"
print(a.upper())   #AA1 

.swapcase()  反转,将字符串内的所有大写字母变成小写字母,小写字母变成大写字母

a = "My Name"
print(a.swapcase())   #mY nAME

.strip()   将字符串内的所有空格和换行都去掉

print("    My Name\n   ".strip(),end="")
print("ok")               #My Nameok  

        用途,由于print后默认的会

1111111\n
1111111\n
1111111\n

if line.strip == "1111": #由于字符串输出后都有一个\n,用strip去掉\n 

.lstrip()   将字符串内的最左边空格和换行都去掉

.rstrip()   将字符串内的最右边空格和换行都去掉

.replace()   替换

print("My name is air".replace("nam","b"))   #My be is air
print("My name name is air".replace("nam","b",1))  #My be name is air

.split()  从左至右,通过定义的分割符,将字符串转换成列表

print("My Name is air".split(" "))   #['My', 'Name', 'is', 'air']
print("My Name is air".split(" ",1))   #['My', 'Name is air']

.rsplit()   从右至左,通过定义的分割符,将字符串转换成列表

print("My Name is air".rsplit(" "))   #['My', 'Name', 'is', 'air']
print("My Name is air".rsplit(" ",1))  #['My Name is', 'air']

.title()   将字符串内的所有单词的首字母都变为大写

print("my Name is air 11".title())    #My Name Is Air 11

作业

三级菜单

1.打印省,市,县三级菜单

2.可返回上一级

3.可随时退出菜单

流程图

 

 讲解前,瞎比写的,竟然写出来了 =  =

dic = {
  "陕西省": {"西安市":["户县","米县"], "咸阳市":["乾县","礼泉"] }, "辽宁省": {"吉林市":["a县","b县"], "沈阳市":["e县","f县"] }, "福建省": {"福州市":["c县","d县"], "荣原市":["x县","z县"] } } e = True while e: for i in enumerate(list(dic.keys()), 1): print(i) count = 1 num_province1 = input(">>>") if num_province1.isdigit(): num_province1 = int(num_province1) city = list(dic.values())[num_province1 - 1].keys() for i in enumerate(city,1): print(i) else: print("请输入正确的命令") elif num_province1 == "quit": print("goodbe") break else: print("请输入正确的命令") continue while True: num_province2 = input(">>>") if num_province2.isdigit() and count == 1: num_province2 = int(num_province2) a = list(dic.values())[num_province1-1] print(list(a.values())[num_province2-1]) print("back(返回上一级2)\n","quit(退出)") count -= 1 continue elif num_province2 == "back" and count == 1: break elif num_province2 == "back" and count == 0: for i in enumerate(city, 1): print(i) count += 1 continue elif num_province2 == "quit": print("goodbey") e = False break else: print("请输入正确的命令") continue

视频中输入的是具体的键,没有用编号,就没看视频,只能绕点弯路,so经过半天折腾,菜单的内容就随便写了下 =  =

一开始用while循环去套if判断,发现行不通。由于循环的格式是先输出在输入下一个菜单的选择,如下

while a:
    menu_level1 = menu.keys()
    for i in enumerate(menu_level1,1):
        print(i)
    frist_input = input("1>>>").strip()
    while a:
        if frist_input.isdigit():
        frist_input = int(frist_input)
        menu_level2 = list(menu.values())[frist_input - 1].keys()    
    else:
        frist_input == "quit"
        print("goodbye")
        break
   while a:...
  

这样会出现一个问题,if frist_input.isdigit():这段语句在执行第一次以外的循环就会报错,因为frist_input值为空。

 

最后改成在if语句里嵌套循环,如下

menu = {
         "a":{
               "a1":{
                   "a11":{
                       "a111":{},
                       "a112":{},
                   },
                   "a12":{
                       "a121":{
                           "a1211":{},
                       },
                       "a122":{},
                       "a123":{
                           "a1231":{},
                       },
                   },
                   "a13":{},
               },
               "a2":{
                   "a21":{
                       "a211":{},
                       "a212":{},
                       "a213":{},
                   },
                   "a22":{},
                   "a23":{},
               },
               "a3":{},
           },
         "b":{
               "b1":{},
           },
         "c":{
               "c1":{},
           },
}
a = True
b = True
while a:
    menu_level1 = menu.keys()
    for i in enumerate(menu_level1,1):
        print(i)
    frist_input = input("1>>>").strip()
    if frist_input.isdigit():
        frist_input = int(frist_input)
        menu_level2 = list(menu.values())[frist_input - 1].keys()
        while a:
            for i in enumerate(menu_level2,1):
                print(i)
            second_input = input("2>>>").strip()
            if second_input.isdigit():
                second_input = int(second_input)
                menu_level3 = list(list(menu.values())[frist_input - 1].values())[second_input - 1].keys()
                while a:
                            for i in enumerate(menu_level3, 1):
                                print(i)
                            thirdly_input = input("3>>>").strip()
                            if thirdly_input.isdigit():
                                thirdly_input = int(thirdly_input)
                                menu_leve4 = list(list(list(menu.values())[frist_input - 1].values())[second_input - 1].values())[thirdly_input - 1].keys()
                                while b:
                                    for i in enumerate(menu_leve4, 1):
                                        print(i)
                                    fourth_input = input("4>>>").strip()
                                    if  fourth_input.isdigit():
                                        while b:
                                            print("inavlid command")
                                            fourth_input = input("4>>>").strip()
                                            if fourth_input.isdigit():
                                                continue
                                            elif fourth_input == "back":
                                                b = False
                                                break
                                            elif fourth_input == "quit":
                                                a,b = False
                                                break
                                            else:
                                                continue
                                    elif fourth_input == "back":
                                        break
                                    else:
                                        fourth_input == "quit"
                                        print("goodbye")
                                        a = False
                                        break
                            elif thirdly_input == "back":
                                break
                            else:
                                thirdly_input == "quit"
                                a = False
                                break
            elif second_input == "back":
                break
            else:
                second_input == "quit"
                print("goodbye")
                a = False
    else:
        frist_input == "quit"
        print("goodbye")
        break

 

视频中使用键选择是有缘由的,代码可以简化,在重新写一遍

for key in menu[frist_input]: 循环遍历字典的键
menu = {
         "a":{
               "a1":{
                   "a11":{
                       "a111":{},
                       "a112":{},
                   },
                   "a12":{
                       "a121":{
                           "a1211":{},
                       },
                       "a122":{},
                       "a123":{
                           "a1231":{},
                       },
                   },
                   "a13":{},
               },
               "a2":{
                   "a21":{
                       "a211":{},
                       "a212":{},
                       "a213":{},
                   },
                   "a22":{},
                   "a23":{},
               },
               "a3":{},
           },
         "b":{
               "b1":{},
           },
         "c":{
               "c1":{},
           },
}
a = True
while a:
    for key in menu:
        print(key)
    frist_input = input("1>>>").strip()
    if frist_input in menu:
        while a:
            for key in menu[frist_input]:
                print(key)
            second_input = input("2>>>").strip()
            if second_input in menu[frist_input]:
                while a:
                    for key in menu[frist_input][second_input]:
                        print(key)
                    thirdly_input = input("3>>>").strip()
                    if thirdly_input in menu[frist_input][second_input]:
                        while a:
                            for key in menu[frist_input][second_input][thirdly_input]:
                                print(key)
                            fourth_input = input("4>>>").strip()
                            print("最后一层")
                            if fourth_input == "b":
                                break
                            else:
                                fourth_input == "q"
                                a = False
                                break
                    elif thirdly_input == "b":
                        break
                    else:
                        thirdly_input == "q"
                        a = False
                        break
            elif thirdly_input == "b":
                break
            else:
                thirdly_input == "q"
                a = False
                break
    else:
        thirdly_input == "q"
        a = False
        break

 

简化写法

menu = {
         "a":{
               "a1":{
                   "a11":{
                       "a111":{},
                       "a112":{},
                   },
                   "a12":{
                       "a121":{
                           "a1211":{},
                       },
                       "a122":{},
                       "a123":{
                           "a1231":{},
                       },
                   },
                   "a13":{},
               },
               "a2":{
                   "a21":{
                       "a211":{},
                       "a212":{},
                       "a213":{},
                   },
                   "a22":{},
                   "a23":{},
               },
               "a3":{},
           },
         "b":{
               "b1":{},
           },
         "c":{
               "c1":{},
           },
}
a = menu   #子层
b = {}     #父层
while True:
    for key in a:
        print(key)
    choice = input(">>>")
    if len(choice) == 0:continue
    if choice in a:
        b = a
        a = a[choice]
    elif choice == "b":
        a = b
    else:
        print("无此项")

这里有一个问题,一次只能返回一层,将b定义为列表,是用append追加

menu = {
         "a":{
               "a1":{
                   "a11":{
                       "a111":{},
                       "a112":{},
                   },
                   "a12":{
                       "a121":{
                           "a1211":{},
                       },
                       "a122":{},
                       "a123":{
                           "a1231":{},
                       },
                   },
                   "a13":{},
               },
               "a2":{
                   "a21":{
                       "a211":{},
                       "a212":{},
                       "a213":{},
                   },
                   "a22":{},
                   "a23":{},
               },
               "a3":{},
           },
         "b":{
               "b1":{},
           },
         "c":{
               "c1":{},
           },
}
current_layer = menu   #子层
parent_layer = []     #父层的键
while True:
    for key in current_layer:
        print(key)
    choice = input(">>>")
    if len(choice) == 0:continue
    if choice in current_layer:
        parent_layer.append(current_layer)
        current_layer = current_layer[choice]
    elif choice == "back":
        if parent_layer:          #if 后直接跟一个字典,当这个字典为空返回False,有内容为True
            current_layer = parent_layer.pop()
    elif choice == "q":
        print("goodbye")
        break
    else:
        print("无此项")

小知识

如上例子

if 后直接跟一个字典,当这个字典为空返回False,有内容为True

for key in dict:    #直接遍历字典内的键

    print(key) 

4.布尔值:True,False

5.元组

在元组内只有一个元素时,最好在元素后面加一个逗号,因为在WEB中单一元组后有一个逗号,才会认为它是一个元组。

a = (1,2,3)
b = (1,)  

6.列表

列表操作

 查看

1.索引

索引位"a"为0,"b"为1,"c"为2,"d"为3,"e"为4

"e"为-1,"d"为-2,"c"为-3,"d"为-4,"e"为-5

索引代表下标,下标代表位置

2.切片

第一种创建方式:
a=["a","b","c","d","e"] #创建列表
第二种创建方式:(当列表内只有一个元素的时候,需要在之后加上一个逗号)
a = list(((a),))
b = list(((a,b)))

 

print(a[1:4]) #从左到右按索引位,取出列表a中1到4,不包括4的之间的每一项。顾头不顾尾
输出
['b', 'c', 'd']

示例 

a=["a","b","c","d","e"]
print(a[1:])#取到最后   ['b', 'c', 'd', 'e']
print(a[1:-1])#取到倒数第二值    ['b', 'c', 'd']
print(a[1:-1:1])#从左到右一个一个取(最后的一个1代表步长)  ['b', 'c', 'd']
print(a[1:4:2])  #从左到右隔一个去取['b', 'd']
print(a[1:-1:2]) #['b', 'd']
print(a[3:0:-2])#步长是有方向的,正数从左到右,负数从右到左   ['d', 'b']
print(a[3:1:-1])#['d', 'c']
print(a[-1:1:-2])#['e', 'c']
print(a[-5])# a

查看列表元素的个数

a = [1,2,3]
print(len(a))
#输出
3

  

3.   .count()  

计算元素在列表中出现的次数(count后面只能跟元素,不能跟切片)

print(["a","a","b","c","d","a"].count("a"))

a=["a","a","b","c","d","a"].count("a")
print(a)
#输出
3

4.  .index()  

根据内容找其对应的索引位置,只能单个取

a=["a1","a2","a3",]
print(a.index("a2"))
#输出
1

5."xx" in  a

a=["a1","a2","a3",]
print("a1" in a)
#输出
True

增加

1. a.append()

追加,在列表a的末尾追加新的内容

a=['a', 'b', 'c', 'd', 'e']
a.append("f")
print(a)
#输出
['a', 'b', 'c', 'd', 'e', 'f']

2. a.insert(index,"内容")   

插入内容到指定的位置

a.insert(1,"a1")
print(a)
#输出
['a', 'a1', 'b', 'c', 'd', 'e']

3. a.extend()

将列表添加到列表中

a=[1,2,3]
b=[4,5,6]
a.extend(b)
print(a)
print(b)
#输出
[1, 2, 3, 4, 5, 6]
[4, 5, 6]
如果需要a,b之和,又不想修改a或b可以使用
print(a+b)
#输出
[1,2,3,4,5,6]

修改

a[index] = "新的值"

a[start:end] = [a,b,c]  

给列表直接赋值

a = [0,1,2,3,4,5,6,7,8,9]
a[1:3] = ["a","b"]
print(a)
#输出
[0,a,b,3,4,5,6,7,8,9]

a = [0,1,2,3,4,5,6,7,8,9]
a[1:4] = ["a","b"]     #切片中有3个值,但只给2个赋值,第3个没有赋值的元素,会被删除
print(a)
#输出
[0,a,b,4,5,6,7,8,9]

删除

1. a.remove("内容") 

列表内置方法,直接删除固定的内容

a.remove("a")  #a.remove(a[0])  只能删除单一的元素
print(a)
#输出
['b', 'c', 'd', 'e']

2.  a.pop(index) 

列表内置方法,删除索引对应的值,并且在删除后,将删除的值返还

b=a.pop(1)
print(a)
print(b)
#输出
['a', 'c', 'd', 'e']
b

3. del a     del a[index]

能够删除任何东西

del a[0]
print(a)
输出
['b', 'c', 'd', 'e']

del a  #将整个列表从内存中删除

4. a.clear()

清空,将列表的内容清空,只剩 []

排序

1.  a.sort()

按照ASNII表排序

不能赋值给变量,并没有return返回一个值 如:a=x.sort()

x=[4,6,2,1,7,9]
x.sort()     
print(x)
#输出
[1, 2, 4, 6, 7, 9] 

 

a=["ba","ab","Xa","me"]
a.sort()
print(a)
#输出
['Xa', 'ab', 'ba', 'me']

a=["ba","ab","Xa","me"]
a.sort(reverse=True)   #反向排序
print(a)
#输出
['me', 'ba', 'ab', 'Xa'] 

2.reverse() 

将列表按倒序排序

不能赋值给变量,并没有return返回一个值 如:a=x.reverse() 

a = [1,2,3]
a.reverse()
print(a)
#输出
[3,2,1]

身份判断

a = [1,2,3]
print(type(a) is list)
#输出
True

列表嵌套

a = [[1,2,3],"a",(a,b)]
print(a[0][1])
#输出
2 

元组

元组被称为只读列表,只能读,不能被修改

a = (1,)
b = (1,2,3,4)
print(a[1:2])
#输出
(2,)

print(a[1])  #同列表,取一个就是值,取两个的话就是元组
2

小知识

多个变量赋值

a,b=[1,2]
print(a)
print(b)
#输出
1
2

作业  

购物车小程序

流程图

讲解前:

commodity_list = ["1.","iphone6s","5800","2.","mac book","9000","3.","coffee","32","4.","python book","80","5","bicyle","1500"]
shopping_list = []
salary = int(input("salary:"))
print(commodity_list[0:3])
print(commodity_list[3:6])
print(commodity_list[6:9])
print(commodity_list[9:12])
print(commodity_list[12:])
while True:
    a=input(">>>>")
    if a.isdigit():
        a=int(a)
        commodity_name = commodity_list[1 + 3 * (a - 1)]
        commodity_price = int(commodity_list[2 + 3 * (a - 1)])
        commodity_number = commodity_list[3 * (a - 1)]
        if commodity_price <= salary:
            shopping_list.append(commodity_list[1 + 3 * (a - 1):2 + 3 * (a - 1)])
            shopping_list.append(commodity_list[2 + 3 * (a - 1)])
            print("已加入",commodity_name,"到你的购物车,当前余额:",salary - commodity_price)
            salary = salary - commodity_price
        else:
            print("余额不足,差",commodity_price - salary)
    else:
        if a == "quit":
            print("您已购买一下商品")
            print(shopping_list)
            print("您的余额为",salary)
            break

讲解后

commodity_list = [("iphone6s",5800),("mac book",9000),("coffee",32),("python book",80),("bicyle",1500)]
salary = int(input("salary:"))
shopping_list = []
for i,v in enumerate(commodity_list,1):   #enumerate(obj,起始编号)  给商品名添加序号
    print(i,">>>",v)                      #这里使用两个临时变量去接受in后的值,i取编号,v取列表中的元组
while True:
    number = input(">>>")
    if number.isdigit():
        number = int(number)
        commodity_price = commodity_list[number - 1][1]
        commodity_name = commodity_list[number-1][0]
        if salary >= commodity_list[number - 1][1]:
            saving = salary - commodity_price     #由于要将变量值引入字符串,方便打印,但%后无法跟运算式,所以另外定义一个变量
            print("已加入",commodity_name,"到你的购物车,当前余额:%s"%saving)
            shopping_list.append(commodity_list[number-1])
            salary = salary - commodity_price
        else:
            f = commodity_price - salary
            print("余额不足,差%s"%f)
    else:
        if number == "quit":
            for i,v in enumerate(shopping_list,1):
                print(i,">>>",v)
            print("您的余额为%s"%salary)
            break

7.字典

字典是python中唯一的映射类型,采用键值对(key-value)形式存储数据。python对key进行哈希函数运算,根据计算的结果决定value的存储地址

字典的两个特点:

1.字典的存储是无序的

2.字典的键是唯一的,并且字典的必须是不可修改的数据类型

可修改的数据类型:列表

不可修改的数据类型:整数,字符串,元组

第一种创建方式:
dic1 = {"name":"air","age":33,"salary":200}

第二种创建方式:(调用函数创建)  当字典内只有一个键值对时,需要在之后加上一个逗号
dic2 = dict((("name","air"),)) 
dic2 = dict((("name","air"),("age",22)))

第三种创建方式:
# 第三种方法
dic = {"name": "air", "age": 23}
dic = dict.fromkeys(["host1","host2","host3"],"test")
print(dic)     #{'host1': 'test', 'host2': 'test', 'host3': 'test'}   #之前的字典被覆盖

#但这种方法存在一个问题,当需要修改"host1"键中的"test2"改为"test3"时,其他所有的键值对中的"test2"都会被修改,如下
dic = dict.fromkeys(["host1","host2","host3"],["test1","test2"])
print(dic)    #{'host1': ['test1', 'test2'], 'host2': ['test1', 'test2'], 'host3': ['test1', 'test2']}
dic["host1"][1] = "test3"
print(dic)    #{'host1': ['test1', 'test3'], 'host2': ['test1', 'test3'], 'host3': ['test1', 'test3']}  

字典操作

1.增加

# 第一种方法
dic = {"name":"air"}
dic["age"] = 23
print(dic) #{"name":"air","age":23}
# 第二种方法
dic1 = dic.setdefault("age",32) #当之前字典内存在age键,那么就不会修改其对应的键值,并且setdefault函数会返回return值
print(dic1) #23

dic2 = dic.setdefault("salary",2000)
print(dic2) #2000

2.查询

通过键,去取内容

dic = {"name":"air","age":23}
print(dic["name"])    #air

.keys 将字典内的键全部取出来

dic = {"name":"air","age":23}
print(dic.keys())   #dict_keys(['name', 'age'])  
print(type(dic.keys()))  # <class 'dict_keys'>   dic.keys()的数据类型
print(list(dic.keys()))  #['name', 'age']    如果想使用可以,将他转换成列表

.valuses() 查看字典内的所有值

dic = {"name":"air","age":23}
print(list(dic.values()))   #['air', 23]

.items() 将字典内的所有键值对做成元组

dic = {"name":"air","age":23}
print(list(dic.items()))    #[('name', 'air'), ('age', 23)]

3.修改

把键取出来重新赋值

dic = {"name": "air", "age": 23}
dic["name"] = "yinghuo"
print(dic)     #{'name': 'yinghuo', 'age': 23}

dic.update()    将后面的字典更新到前面的字典里,并且它是没有返回return值

dic = {"name": "air", "age": 23}
dic2 = {"1":111,"2":222}
dic.update(dic2)
print(dic)     #{'name': 'air', 'age': 23, '1': 111, '2': 222}

当被更新进去的字典内,存在相同的键,则键值会被替换掉

dic = {"name": "air", "age": 23}
dic3 = {"1":111,"2":222,"name":"yinghuo"}
dic.update(dic3)
print(dic)       #{'name': 'yinghuo', 'age': 23, '1': 111, '2': 222}

4.删除

.clear() 清空字典内的所有键值对

dic = {"name": "air", "age": 23}
dic.clear()
print(dic)    #{}  

del 通过删除键,来删除整个键值对

删除单一的键值对

dic = {"name": "air", "age": 23}
del dic["name"]
print(dic)    #{'age': 23}

删除整个字典

dic = {"name": "air", "age": 23}
del dic  

.pop()  通过删除键,来删除整个键值对,并将删除的值返还

dic = {"name": "air", "age": 23}
a=dic.pop("name")
print(dic)    #{'age': 23}
print(a)      #air

.popitem() 随机删除,并将删除的值返还

dic = {"name": "air", "age": 23}
a = dic.popitem()
print(a)     #('age', 23)
print(dic)   #{'name': 'air'}

5.排序

根据键排序

dic = {"3":33,"5":55,"2":22}
print(sorted(dic))    #['2', '3', '5']
print(sorted(dic.values()))   #[22, 33, 55]
print(sorted(dic.items()))    #[('2', 22), ('3', 33), ('5', 55)]

6.字典的遍历

dic = {"name":"air","age":11}

for i in dic:              #这种方式最好
    print(i,dic[i])

for i,v in dic.items():  #这种方式多了一次转换
    print(i,v)
posted @ 2017-10-11 18:58  左手萤火  阅读(162)  评论(0)    收藏  举报