Python入门笔记(三)




前些天发现了一个巨牛的人工智能学习网站,通俗易懂,风趣幽默,忍不住分享一下给大家。
点击跳转:人工智能从入门到精通教程




本文电子版获取方式:
「Python入门笔记(三).pdf」,复制整段内容,打开最新版「夸克APP」即可获取。
链接:https://pan.quark.cn/s/93216671fe07


第八章 字典dict

和list比较,dict有以下几个特点:

  1. 查找和插入的速度极快,不会随着key的增加而变慢;
  2. 需要占用大量的内存,内存浪费多。

而list相反:

  1. 查找和插入的时间随着元素的增加而增加;
  2. 占用空间小,浪费内存很少。

所以,dict是用空间来换取时间的一种方法。


  1. 字典是无序的,是可变序列
  2. 用花括号括起来
  3. 字典是一系列的键-值对(key-value),值可以是数字、字符串、列表乃至字典。
  4. 字典是一种动态结构,可随时在其中添加键-值对。要添加键-值对,可依次指定字典名、用方括号括起来键和相关联的值
  5. dict的key必须是不可变对象。
  6. 键不可重复,值可以重复

8.1 创建字典:{}、dict()、字典生成式、zip()

  1. 花括号
  2. 使用内置函数dict()
  3. 字典生成式

dict()
例1:

dict1 = dict(name='zdb', age='1')
print(dict1)
{'name': 'zdb', 'age': '1'}

例2

a = (('F',70),('i',105),('s',115),('h',104),('C',67))
print(type(a))

dict3 = dict((('F',70),('i',105),('s',115),('h',104),('C',67)))   #元组转换字典
print(dict3)
<class 'tuple'>
{'F': 70, 'i': 105, 's': 115, 'h': 104, 'C': 67}

创建空字典

print(dict())
{}

字典生成式

公式: d = {item: price for item, price in zip(items, prices)}

items = ['Fruits', 'Books', 'Others']
prices = [96, 78, 85, 100]

d = {item: price for item, price in zip(items, prices)}
print(d)
{'Fruits': 96, 'Books': 78, 'Others': 85}

zip():将两个列表对应位置的值括起来

list1=[3,2,1,6,5,4,9,9,9]
list2=[1,2,3,4,5,6]
print(zip(list1,list2))
print(list(zip(list1,list2)))
<zip object at 0x000001C3AF8CCB88>
[(3, 1), (2, 2), (1, 3), (6, 4), (5, 5), (4, 6)]

8.2 获取键对应的值:get()

1. 通过访问键得到值
例1

alien_0 = {'color':'green', 'points':5}
print(alien_0['color'])       #输出color对应的值
print(alien_0['points'])
green
5

例2

scores = {'张三':100, '李四':98, '王二':45}
print(scores['张三'])
100

.get()

  • 1.字典中有这个键则输出值
  • 2.字典没有这个键则输出none
  • 3.可以自定义没有这个键时输出的内容

例1

scores = {'张三':100, '李四':98, '王二':45}
print(scores.get('张三'))
print(scores.get('麻子'))
print(scores.get('麻子', '没有'))
100
None
没有

8.3 in, not in判断键是否在字典中

scores = {'张三':100, '李四':98, '王二':45}
print('张三' in scores)
print('麻子' not in scores)
True
True

8.4 增加键值对:fromkeys()、setdefault()、update()

1.直接增加键值对

例1:添加两个键

alien_0 = {'color':'green', 'points':5}
print(alien_0)

alien_0['x_position'] = 0       #添加键-值对
alien_0['y_position'] = 25
print(alien_0)
{'color': 'green', 'points': 5}
{'color': 'green', 'points': 5, 'x_position': 0, 'y_position': 25}

例2:添加键和值

  • 给字典中没有的键赋予值就是添加键值对
  • 给字典中有的键赋予新值就是修改键所对应的值
dict4 = dict(name='zdb', 性别='男')
print(dict4)

dict4['name'] = 'zz'
print(dict4)

dict4['民族'] = '汉'
print(dict4)
{'name': 'zdb', '性别': '男'}
{'name': 'zz', '性别': '男'}
{'name': 'zz', '性别': '男', '民族': '汉'}

例3. 空字典中添加键-值对

alien_0 = {}

alien_0['color'] = 'green'
alien_0['prints'] = 5
print(alien_0)
{'color': 'green', 'prints': 5}

2.fromkeys()创建键-值对
例1

dict1 = dict.fromkeys(range(5),'zdb')
print(dict1)
{0: 'zdb', 1: 'zdb', 2: 'zdb', 3: 'zdb', 4: 'zdb'}

例2

dict1 = {}
print(dict1.fromkeys((1,2,3)))
print(dict1.fromkeys((1,2,3),'number'))         #三个键对应的值一样
print(dict1.fromkeys((1,2,3),('one','two','three')))
print(dict1.fromkeys((1,3),'数字'))
{1: None, 2: None, 3: None}
{1: 'number', 2: 'number', 3: 'number'}
{1: ('one', 'two', 'three'), 2: ('one', 'two', 'three'), 3: ('one', 'two', 'three')}
{1: '数字', 3: '数字'}

3.setdefault()添加键和值

a = {1:'one',2:'two',3:'three',4:'four'}   #字典没有顺序
a.setdefault('小白')   #添加键
print(a)

a.setdefault(5,'five')  #添加键和值
print(a)
{1: 'one', 2: 'two', 3: 'three', 4: 'four', '小白': None}
{1: 'one', 2: 'two', 3: 'three', 4: 'four', '小白': None, 5: 'five'}

4.update()用字典A更新字典B的键值对

a = {1:'one',2:'two',3:'three',4:'four'}   # 字典没有顺序
b = {'小白':'狗'}
a.update(b)           # 用b更新a
print(a)
{1: 'one', 2: 'two', 3: 'three', 4: 'four', '小白': '狗'}



8.5 删除键值对:del语句、clear()、pop()、popitem()

1.del永久性删除,删除指定的键值对
例:

alien_0 = {'color':'green', 'points':5}
print(alien_0)

del alien_0['points']     #删除键
print(alien_0)
{'color': 'green', 'points': 5}
{'color': 'green'}

2、.clear()清空字典,永久的,清空后为空字典

dict1 = dict.fromkeys(range(5),'zdb')
print(dict1)
dict1.clear()
print(dict1)
{0: 'zdb', 1: 'zdb', 2: 'zdb', 3: 'zdb', 4: 'zdb'}
{}

3. pop()删除键值对,永久的

a = {'a':'one', 'b':'two', 'c':'three', 'd':'four'}   #字典没有顺序
a.pop('b')
print(a)
{'a': 'one', 'c': 'three', 'd': 'four'}

4.popitem()删除最后一个键值对,永久的

a = {1:'one',2:'two',3:'three',4:'four'}   #字典没有顺序
print(a.popitem())    #输出最后一个
print(a)
(4, 'four')
{1: 'one', 2: 'two', 3: 'three'}

8.6 遍历键、值、键值对:keys()、values()、items()

1. 遍历键
方法一

scores = {'张三': 100, '李四': 98, '王二': 45}
for i in scores:
    print(i)
张三
李四
王二

方法二:keys()

favorite_language = {
    'jen':'python',
    'sarah':'c',
    'edward':'ruby',
    'phil':'python'
    }

for name in favorite_language.keys():    #两个变量随便取名 
    print(name.title())
Jen
Sarah
Edward
Phil

例2

favorite_language = {
    'jen':'python',
    'sarah':'c',
    'edward':'ruby',
    'phil':'python'
    }

friends = ['phil', 'sarah']
for name in favorite_language.keys():    #遍历键
    print(name.title())

    if name in friends:
        print("我朋友" + name.title() + "最喜欢的语言是:" +favorite_language[name].title() + '!')
Jen
Sarah
我朋友Sarah最喜欢的语言是:C!
Edward
Phil
我朋友Phil最喜欢的语言是:Python!

例3

scores = {'张三': 100, '李四': 98, '王二': 45}
keys = scores.keys()
print(list(keys))
['张三', '李四', '王二']

2.遍历值
方法一

scores = {'张三': 100, '李四': 98, '王二': 45}
for i in scores:
    print(scores[i])
100
98
45

方法二

scores = {'张三': 100, '李四': 98, '王二': 45}
for i in scores:
    print(scores.get(i))

方法三 :.values()

favorite_language = {
    'jen':'python',
    'sarah':'c',
    'edward':'ruby',
    'phil':'python'
    }

print('以下语言被提到过:')
for language in favorite_language.values():  #遍历所有的值
    print(language.title())
以下语言被提到过:
Python
C
Ruby
Python

3. 遍历键值对
方法一

scores = {'张三': 100, '李四': 98, '王二': 45}
for i in scores:
    print(i, scores[i], scores.get(i))
张三 100 100
李四 98 98
王二 45 45

方法二:.items():遍历所有的键-值对
例1:

user_0 = {
    '姓名': 'zdb',
    '姓': 'z',
    '名': 'db',
    }
for key, value in user_0.items():  # 两个变量随便取名
    print('Key:' + key)            # 拼接输出
    print('Value: ' + value)
Key:姓名
Value: zdb
Key:姓
Value: z
Key:名
Value: db

例2

favorite_language = {
    'jen': 'python',
    'sarah': 'c',
    'edward': 'ruby',
    'phil':' python'
    }

for name, language in favorite_language.items():    #两个变量随便取名
    print(name.title() + "'最喜欢的语言是:" +
          language.title() + '.')
Jen'最喜欢的语言是:Python.
Sarah'最喜欢的语言是:C.
Edward'最喜欢的语言是:Ruby.
Phil'最喜欢的语言是: Python.

8.7 字典、列表相互嵌套

1.在列表中存储字典:[{}, {}, {}]

alien_0 ={'color':'green', 'points':5}
alien_1 ={'color':'yellow', 'points':10}
alien_2 ={'color':'red', 'points':15}

aliens = [alien_0, alien_1, alien_2]    #列表中嵌套字典

for alien in aliens:
    print(alien)
{'color': 'green', 'points': 5}
{'color': 'yellow', 'points': 10}
{'color': 'red', 'points': 15}

创建30个外星人

#创建一个用于存储外星人的空列表
aliens = []

#创建30个绿色的外星人
for alien_number in range(30):       #0到29,循环30下
    new_alien = {'color':'green', 'points':5, 'speed':'slow'}
    aliens.append(new_alien)         #添加了30个外星人

#显示当前五个外星人
for alien in aliens[:5]:             #循环5下
    print(alien)
print('...')

#显示创建了多少个外星人
print("Total number of aliens: " + str(len(aliens)))
{'color': 'green', 'points': 5, 'speed': 'slow'}
{'color': 'green', 'points': 5, 'speed': 'slow'}
{'color': 'green', 'points': 5, 'speed': 'slow'}
{'color': 'green', 'points': 5, 'speed': 'slow'}
{'color': 'green', 'points': 5, 'speed': 'slow'}
...
Total number of aliens: 30

将前三个外星人修改为黄色

#创建一个用于存储外星人的空列表
aliens = []

#创建30个绿色的外星人
for alien_number in range(30):
    new_alien = {'color':'green', 'points':5, 'speed':'slow'}
    aliens.append(new_alien)

for alien in aliens[0:3]:             #前三个
    if alien['color'] == 'green':     #修改颜色,速度,点数
        alien['color'] = 'yellow'
        alien['speed'] = 'medium'
        alien['points'] = 10

#显示当前五个外星人
for alien in aliens[:5]:             #循环前五个
    print(alien)
print('...')

#显示创建了多少个外星人
print("Total number of aliens: " + str(len(aliens)))
{'color': 'yellow', 'points': 10, 'speed': 'medium'}
{'color': 'yellow', 'points': 10, 'speed': 'medium'}
{'color': 'yellow', 'points': 10, 'speed': 'medium'}
{'color': 'green', 'points': 5, 'speed': 'slow'}
{'color': 'green', 'points': 5, 'speed': 'slow'}

2.在字典中存储列表:{[], [], []}
例1

#存储所点披萨的信息
pizza = {
    'crust':'thick',
    'toppings':['mushrooms', 'extra cheese']      #列表在字典中
    }

#概述所点的披萨
print("You ordered a " + pizza['crust'] + "-crust pizza" +
      "with the following toppings:")

for topping in pizza['toppings']:                #遍历键topping所对应的值
    print('\t' + topping)
You ordered a thick-crust pizzawith the following toppings:
	mushrooms
	extra cheese

例2

favorite_languages = {
    'jen':['python', 'ruby'],
    'sarah':['c'],
    'edward':['ruby', 'go'],
    'phil':['python', 'haskell'],
    }

for name, languages in favorite_languages.items():    #两个变量随便取名
    print('\n' + name.title() + "'s favorite languages are:")
    for language in languages:
        print("\t" + language.title())
Jen's favorite languages are:
	Python
	Ruby

Sarah's favorite languages are:
	C

Edward's favorite languages are:
	Ruby
	Go

Phil's favorite languages are:
	Python
	Haskell

在字典中存储字典:{{}, {}, {}}

users = {
    'aeinstein':{                    #字典在字典中   
        'first':'albert',
        'last':'einstein',
        'location':'princeton',
        },

    'mxurie':{
        'first':'marie',
        'last':'curie',
        'location':'paris',
    },
        }

for username, user_info in users.items():     #遍历键-值对
    print("\nUsername: " + username)          #输出字典中的字典
    full_name = user_info['first'] + ' ' + user_info['last']
    location = user_info['location']

    print("\tFull name: " + full_name.title())
    print("\tlocation: " + location.title())
Username: aeinstein
	Full name: Albert Einstein
	location: Princeton

Username: mxurie
	Full name: Marie Curie
	location: Paris

8.8 字典中索引键对应的值:.index()

brand = ['甲','乙','丙']
slogan = ['a','b','c']
print('甲是什么:',slogan[brand.index('甲')])
print('乙是什么:',slogan[brand.index('乙')])
print('丙是什么:',slogan[brand.index('丙')])
甲是什么: a
乙是什么: b
丙是什么: c

8.9 备份字典:copy()

改变原来的,等号=赋值的会改变,但copy()的永远不变

id()
查询ID,用来判断是否改变

例1: 不管怎么改变a, c永远不变;重新等号赋值a,不影响最初等号赋值的b

a = {'姓名':'zdb'}
b_fuzhi = a         # 赋值,要变两个都变,ID相同
c_copy = a.copy()   # 与a,b的ID不同
print(id(a))           # 原来的
print(id(b_fuzhi))     # 与a的一样
print(id(c_copy))      # 与a的不一样

a = {}                 # 再次赋值改变a
print(a)               # a现在是空字典
print(b_fuzhi)         # 与上面的b_fuzhi相同
print(c_copy)          # 与上面的c_copy相同
print(id(a))           # 跟最初始的a相比,变了
print(id(b_fuzhi))     # 与上面的b_fuzhi相同
print(id(c_copy))      # 与上面的c_copy相同
1585541151464
1585541151464
1585541151544

{}                    #变了
{'姓名': 'zdb'}    #没变
{'姓名': 'zdb'}    #没变
1585541152584   #变了
1585541151464   #没变
1585541151544   #没变

例2:这里用clear清除a
不管怎么改变a,c永远不变;clear清除a,这里之前等号赋值的b也会被清除
只有重新赋值a才会变ID,用clear清除a,a前后的ID不会改变

a = {'姓名':'zdb'}
b = a          # 赋值,要变两个都变,ID相同
c = a.copy()   # 与a、b的ID不同
print(id(a))   # 原来的
print(id(b))   # 与a的一样
print(id(c))   # 与a的不一样

a.clear()      # 清除a
print(a)       # 空字典
print(b)       # 空字典
print(c)       # 与上面的c相同,不是空的
print(id(a))   # 与最初始的a没变
print(id(b))   # 与最初始的b没变,还与a相同
print(id(c))   # 死也不变
2709389179624
2709389179624
2709389179704         #copy的内容不变

{}
{}                    #赋值的也清除了
{'姓名': 'zdb'}    #copy的没变 
2709389179624
2709389179624        #与a原来的ID一直一样
2709389179704

例3a等号赋值给b,不管是a还是b增加或减少元素,另外一个都会跟着改变,但是ID永远不变

a = {'姓名':'zdb'}    #字典里面没有顺序
b = a            # 等号赋值
c = a.copy()     # 这里就不在举例这个了,永远不变
print(id(a))     # 原来的
print(id(b))     # 与a的相同

b[2] = 'z'       #b增加元素,a也会增加
print(a)
print(b)
print(id(a))
print(id(b))

a[3] = '猪'       #a增加元素,b也会增加
print(a)
print(b)
print(id(a))
print(id(b))

a.pop(3)         #删除a的键3,b跟着删除
print(a)
print(b)
print(id(a))
print(id(b))

a.pop(2)        #删除a的键2,b跟着删除
print(a)
print(b)
print(id(a))
print(id(b))
1734662028008
1734662028008

{'姓名': 'zdb', 2: 'z'}
{'姓名': 'zdb', 2: 'z'}
1734662028008
1734662028008

{'姓名': 'zdb', 2: 'z', 3: '猪'}
{'姓名': 'zdb', 2: 'z', 3: '猪'}
1734662028008
1734662028008

{'姓名': 'zdb', 2: 'z'}
{'姓名': 'zdb', 2: 'z'}
1734662028008
1734662028008

{'姓名': 'zdb'}
{'姓名': 'zdb'}
1734662028008
1734662028008



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

zdb呀

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值