首页 > 编程语言 > 详细

Python编程 从入门到实践-6字典上

时间:2020-03-13 13:51:58      阅读:77      评论:0      收藏:0      [点我收藏+]

笔记出处(学习UP主视频记录) https://www.bilibili.com/video/av35698354?p=11

#列表
cars = [bmw, suzuki]
#元组
dimensions = (200,50)

6.1 一个简单的字典

alien_0 = {color: green, points: 5}

print (alien_0[color])
print (alien_0[points])

green
5

6.2 使用字典

alien_0 = {color: green, points: 5}

print (alien_0[color])
print (alien_0[points])

green
5

6.2.1 访问字典中的值

alien_0 = {color: green, points: 5}

new_points = alien_0[points]
print ("You just earned " + str(new_points) + " points!")

You just earned 5 points!

6.2.2 添加键-值对

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

#外星人的X坐标和Y坐标

alien_0[x_postion] = 0
alien_0[y_position] = 25
print (alien_0)

{‘color‘: ‘green‘, ‘points‘: 5}
{‘color‘: ‘green‘, ‘points‘: 5, ‘x_postion‘: 0, ‘y_position‘: 25}

6.2.3 先创建一个空字典

alien_0 = {}

#分行添加各个键值对

alien_0[color] = green
alien_0[points] = 5

print (alien_0)

{‘color‘: ‘green‘, ‘points‘: 5}

6.2.4 修改字典中的值

alien_0 = {color: green}
#现在外星人的颜色是
print ("The alien is " + alien_0[color] + ".")

alien_0[color] = yellow
#修改了外星人的颜色为黄色
print ("The alien is now " + alien_0[color] + ".")

The alien is green.
The alien is now yellow.

#对一个能够以不同速度移动的外星人的位置进行跟踪
#存储外星人的当前速度,并确定该外星人将向右移动多远

alien_0 = {x_position: 0, y_position: 25, speed: medium}
print ("Original x-position: " + str(alien_0[x_position]))

#向右移动外星人
#据外星人当前速度决定将其移动多远

if alien_0[speed] == slow:
    x_lincrement = 1
elif alien_0[speed] == medium:
    x_lincrement = 2
else:
    #这个外星人的速度一定很快
    x_increment = 3

#新位置等于老位置加上增量
alien_0[x_position] = alien_0[x_position] + x_lincrement
print ("New x_position: " + str(alien_0[x_position]))

Original x-position: 0
New x_position: 2

6.2.5 删除键-值对

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

del alien_0[points]
print (alien_0)

{‘color‘: ‘green‘, ‘points‘: 5}
{‘color‘: ‘green‘}

6.2.6 由类似对象组成的字典

#调查4个人,询问他们最喜欢的编程语言是什么

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

print ("Sarach‘s favorite language is " +
       favorite_languages[sarah].title()+
       ".")

Sarach‘s favorite language is C.

Python编程 从入门到实践-6字典上

原文:https://www.cnblogs.com/nxopen2018/p/12485007.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!