python: data structure-tuples and namedtuples
阿新 • • 發佈:2018-11-25
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