python: data structure-tuples and namedtuples

tuples

  • tuples are objects that can store a specific number of other objects in order, and are immutable. the benefit of tuple's immutability is they can be used as keys in dictionaries, and in other locations where an object requires a hash value.
  • tuples should generally store values that are somehow different from each other. the primary purpose of a tuple is to aggregate different pieces of data together into one container.
  • try to use tuples only when you know that all the values are going to be useful at once and it's normally going to be unpacked when it is accessed.
  • valid ways to declare a tuple:
>>> stock = "FB", 75, 74, 76
>>> stock1= ("FB", 75, 74, 76)
  • tuple unpacking: the tuple can be unpacked by variables that with the total number exactly the same length of the tuple
>>> symbol, current, high, low=stock

namedtuples

  • a great way to group read-only data together. namedtuple is also immutable.
  • construct a named tuple: namedtuple constructor accepts two arguments. the first is an ID for the named tuple, and the second is a string of space-separated (or comma separated) attributes that the named tuple will have.
# import namedtuple
from collections import namedtuple

# describe the named tuple by giving it a name and outlining its attributes
stock = namedtuple("stock", "symbol, current, high, low")
""" this returns a class-call like object"""

# instantiate the tuple as many times as we want:
stock_info = stock("FB", 100, 101, 99)

>>> stock_info.current
100

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值