zoukankan      html  css  js  c++  java
  • Python-为元组中每个元素命名

    学生信息系统:

           (名字,年龄,性别,邮箱地址)

           为了减少存储开支,每个学生的信息都以一个元组形式存放

           如:

           ('tom', 18,'male','tom@qq.com' )

           ('jom', 18,'mal','jom@qq.com' ) .......

           这种方式存放,如何访问呢?

    普通方法:

    #!/usr/bin/python3
    
    student = ('tom', 18, 'male', 'tom @ qq.com' )
    print(student[0])
    if student[1] > 12:
        ...
    if student[2] == 'male':   
        ...

           出现问题,程序中存在大量的数字index,可阅读性太差,无法知道每个数字代替的含义

    如何解决这个问题?

           方法1:

    #!/usr/bin/python3
    
    # 给数字带上含义,和元组中一一对应
    name, age, sex, email = 0, 1, 2, 3                         
    # 高级:name, age, sex, email = range(4)
    student = ('tom', 18, 'male', 'tom @ qq.com' )
    print(student[name])
    if student[age] > 12:
         print('True')
    if student[sex] == 'male':
        print('True')

                  这样就直白多了,看名字就知道取什么元素

           方法2:

      通过 collections库的 nametuple模块

    #!/usr/bin/python3
    
    from collections import namedtuple
    
    # 生成一个Student类
    Student = namedtuple('Student', ['name', 'age', 'sex', 'email'])
    
    # 生成一条信息对象
    s = Student('tom', 18, 'male', 'tom@qq.com')
    
    # 通过类对象进行取数据
    print(s.name, s.age, s.sex, s.email)
    
  • 相关阅读:
    我不喜欢的 Rust 特性 (之一) eager drop
    为 Windows Phone 8.1 app 解决“The type does not support direct content.”的问题
    输入10个互不相同的数字并分成5对,问有多少种分法。
    code wars quiz: toInteger
    my first emacs custom key binding
    http协议消息报头学习笔记
    移动端经常遇到的小bug
    js小技巧
    ajax
    js正则表达
  • 原文地址:https://www.cnblogs.com/2bjiujiu/p/7236199.html
Copyright © 2011-2022 走看看