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


    笔记出处(学习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.

    Caesar卢尚宇

    2020年3月13日

  • 相关阅读:
    星空雅梦
    星空雅梦
    星空雅梦
    星空雅梦
    星空雅梦
    星空雅梦
    网络爬虫的相关综述
    HTTP协议和几种常见的状态码
    在php中,如何将一个页面中的标签,替换为用户想输出的内容
    php学习第一讲----php是什么?
  • 原文地址:https://www.cnblogs.com/nxopen2018/p/12485007.html
Copyright © 2020-2023  润新知