backlinks to this page:
Plugin Backlinks: Nothing was found.
Github:
named tuples
is part of the collections
module and must be imported before they can be used.
Named tuple is a data structure like a tuple, but each element has a name like the instance attributes of a class.
Documentation:
# example code:
from collections import namedtuple Color = namedtuple("Color", "r g b alpha") # note that Color and "Color" must be identical. # usage examples red = Color(r=250, g=0, b=0, alpha=alpha) print(red.alpha) blue = Color(r=50, g=0, b=255, alpha=alpha)
>>> c = {"r": 50, "g": 205, "b": 50, "alpha": alpha} >>> Color = namedtuple("Color", c) # c is the field list for the named tuple here >>> Color(**c) Color(r=50, g=205, b=50, alpha=0)
>>> blue = Color(r=0, g=0, b=255, alpha=1.0) >>> blue._asdict() {'r': 0, 'g': 0, 'b': 255, 'alpha': 1.0}
from collections import namedtuple from operator import attrgetter # define named Tuple Color = namedtuple("Color", "r g b alpha") # unsorted list of named tuple mycolors = [ Color(r=50, g=205, b=50, alpha=0.1), Color(r=50, g=205, b=50, alpha=0.5), Color(r=50, g=0, b=0, alpha=0.3) ] sorted(mycolors, key=attrgetter("alpha")) # pretty output, sorted by alpha value for c in mycolors: print(c) # output should be: #Color(r=50, g=205, b=50, alpha=0.1) #Color(r=50, g=205, b=50, alpha=0.5) #Color(r=50, g=0, b=0, alpha=0.3)