本文整理汇总了Python中odict.OrderedDict类的典型用法代码示例。如果您正苦于以下问题:Python OrderedDict类的具体用法?Python OrderedDict怎么用?Python OrderedDict使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了OrderedDict类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: JobTracker
class JobTracker(object):
def __init__(self, name, trackers, cls=Monitor):
self.name = name
self.count = 0
self.trackers = OrderedDict()
for n, getter in trackers:
mon = cls("%s: %s" % (name, n))
self.trackers[n] = (mon, getter)
def __getattr__(self, attr):
if attr in self.trackers:
return self.trackers[attr][0]
else:
raise AttributeError
def record(self, agent, job):
for mon, getter in self.trackers.itervalues():
mon.observe(getter(agent, job))
self.count += 1
def report(self):
for mon, _ in self.trackers.itervalues():
print self._report(mon)
def _report(self, tally):
s = "mean %s: %.2f (%.2f)"
if tally.count():
vars = (tally.name, tally.mean(), math.sqrt(tally.var()))
else:
vars = (tally.name, 0, 0)
return s % vars
示例2: get_stats
def get_stats(self, dim, prefix=''):
"""Get various 1d statistics for the datatable.
"""
def add_stat(stats, key, val):
stats[prefix+key] = val
def get_stat(stats, key):
return stats[prefix+key]
#print dim
#print self.num_cells
#print self.data
p = self.get_points(dim)
s = OrderedDict()
add_stat(s, 'num_cells', self.num_cells)
add_stat(s, 'min', np.min(p))
add_stat(s, 'max', np.max(p))
add_stat(s, 'average', np.average(p))
add_stat(s, 'std', np.std(p))
add_stat(s, 'median', np.median(p))
add_stat(s, 'gaussian_fit',
self.gaussian_pdf_compare(
dim, 100,
get_stat(s, 'average'),
get_stat(s, 'std')))
keys = s.keys()
vals = np.array([s.values()])
ret = DataTable(vals, keys, name=self.sub_name('stats for %s' % dim))
ret.properties['original_table'] = self
return ret
示例3: _flatten_dictionary
def _flatten_dictionary(self, params, parent=None):
"""
Flatten a hierarchical dictionary into a simple dictionary.
>>> self._flatten_dictionary({
"test": {
"foo": 12,
"bar": "hello",
},
"baz": False
})
{
"test[foo]": 12,
"test[bar]": hello,
"baz": False
}
"""
data = OrderedDict()
for key, val in params.items():
full_key = parent + "[" + key + "]" if parent else key
if isinstance(val, dict):
data.update(self._flatten_dictionary(val, full_key))
else:
data[full_key] = val
return data
示例4: __init__
def __init__(self, name):
self.name = name
self.sensitivities = OrderedDict()
self.baseClassifications = OrderedDict()
self.rawToTrans = OrderedDict()
self.transToRaw = OrderedDict()
self.groups = OrderedDict()
示例5: __add__
def __add__(self,rhs):
"Add histograms in rhs to current sample and create a new sample"
s = self.Clone()
print 'Plotter ### in add for Label = ', self.Label
# Deal with samples not having hists (e.g. files not found)
if len(rhs._HistDict)==0: return s
if len(s._HistDict)==0: return rhs
#make copies so elements can be removed without lasting damage
RhsHistDict = rhs._HistDict
SHistDict = s._HistDict
# make a new OrderedDict that contains only the hists that are in both rhs and self and fill it with those in self
MinHistDict = OrderedDict()
for key, obj in SHistDict.iteritems():
if SHistDict.has_key(key) and RhsHistDict.has_key(key): MinHistDict[key]=obj
if testVerbose: print 'Sample ### MinHistDict = ', MinHistDict
#now add rhs to the new ordered dict
for key, obj in MinHistDict.iteritems():
MinHistDict[key].Add(RhsHistDict[key])
self._OpSetProperties(s, rhs, '+')
#alter the hist dict of copy of self by setting it to the new hist dict created above and return it
s._HistDict = MinHistDict
return s
示例6: __init__
def __init__(self, method='POST', action='', submitLabel='Submit', attrs=None):
'''Initialize a new, empty form instance.
@param method: the form method attribute (i.e. "GET" or "POST")
@type method: str
@param action: the form action attribute. This will often be the empty
@type action: str
string ("self-submission"), for simplified validation and error message display.
@param submitLabel: the text of the final submit button.
@type submitLabel: str
@param attrs: a dictionary of attribute names and values for the form
element (i.e. the "class" or "id" attributes). The I{method} and
I{action} attributes can be set here, or through their parameters (which
are provided simply as a convenience; if set on both, the values here
take precedence.
@type attrs: dict
'''
OrderedDict.__init__(self)
self.schema = schema.Schema()
self.schema.fields = self
self.attrs = {'method':method, 'action':action}
if attrs:
self.attrs.update(attrs)
self.submitLabel = submitLabel
示例7: sort_recursive
def sort_recursive(dictionary):
"""
Recursively sorts nested dictionaries. Should not be applied if the
structures are nested too deeply and/or there is even the remote
possibility that the nesting of the passed dictionary contains a cyclic
structure.
Args:
dictionary (dict): A python dictionary
Returns:
A recursively sorted dictionary
Example:
>>> dict = { 'a': '2', 'c': 3, 'b': { 'e': 4, 'd': 1 }, 'f': 5}
>>> sort_recursive(dict)
OrderedDict([('a', '2'), ('b', OrderedDict([('d', 1), ('e', 4)])), ('c', 3), ('f', 5)])
"""
sorted_list = OrderedDict(sorted(dictionary.items(), key = lambda x: x[0]))
# TODO test for cyclic structures.
for key, value in sorted_list.items():
if type(value) is dict:
sorted_list[key] = sort_recursive(value)
return sorted_list
示例8: startElement
def startElement(self, name, attrs):
self.path.append((name, attrs or None))
if len(self.path) > self.item_depth:
self.stack.append((self.item, self.data))
attrs = OrderedDict((self.attr_prefix+key, yaml_eval(value))
for (key, value) in attrs.items())
self.item = self.xml_attribs and attrs or None
self.data = None
示例9: merge_hists
def merge_hists(hists_d, merge_groups, order=PhysicsProcess.desired_plot_order):
"""
Merges the dictionary of input histograms according to the merge rules, which are specified
as a key-value dictionary, where the key is the target and value a list of (regular) expressions
to merge under the key.
For example, {
"WJets": ["W[1-4]Jets_.*"],
"tchan": ["T_t_ToLeptons", "Tbar_t_ToLeptons"],
} will perform the corresponding merges. The values of the merge dict are the keys of the input histogram dict.
returns - a dictionary with the merged histograms. Optionally you can specify a list with the desired order of the keys.
"""
for v in hists_d.values():
if not isinstance(v, Hist) and not isinstance(v, ROOT.TH1I) and not isinstance(v, ROOT.TH1F) and not isinstance(v, Hist2D) and not isinstance(v, ROOT.TH2I) and not isinstance(v, ROOT.TH2F):
raise ValueError("First argument(hists_d) must be a dict of Histograms, but found %s" % v)
out_d = OrderedDict()
logger.debug("merge_hists: input histograms %s" % str(hists_d))
for merge_name, items in merge_groups.items():
logger.debug("Merging %s to %s" % (items, merge_name))
matching_keys = []
for item in items:
t = filter(lambda x: re.match(item + "$", x), hists_d.keys())
matching_keys += t
logger.debug("Matched %s to %s" % (str(t), item))
if len(matching_keys)==0:
continue
logger.debug("Merging matched %s" % str(matching_keys))
hist = hists_d[matching_keys[0]].Clone()
for item in matching_keys[1:]:
hist.Add(hists_d[item])
out_d[merge_name] = hist
out_d[merge_name].SetTitle(merge_name)
out_d[merge_name].SetName(merge_name)
out_d_ordered = OrderedDict()
for elem in order:
try:
out_d_ordered[elem] = out_d.pop(elem)
if hasattr(PhysicsProcess, merge_name):
if type(getattr(PhysicsProcess, merge_name)) is dict: #take nominal name if multiple options
out_d_ordered[elem].SetTitle(getattr(PhysicsProcess, merge_name)["nominal"].pretty_name)
else: #regular
out_d_ordered[elem].SetTitle(getattr(PhysicsProcess, merge_name).pretty_name)
except KeyError: #We don't care if there was an element in the order which was not present in the merge output
pass
#Put anything that was not in the order list simply to the end
for k, v in out_d.items():
out_d_ordered[k] = v
return out_d_ordered
示例10: separate_tables_by_time
def separate_tables_by_time(self, tables, time_col):
return [tables], [range(len(tables))]
time_to_tables = OrderedDict()
time_to_idx = OrderedDict()
for i, time in enumerate(time_col):
time_to_tables.setdefault(time, []).append(tables[i])
time_to_idx.setdefault(time, []).append(i)
return time_to_tables.values(), time_to_idx.values()
示例11: __init__
def __init__(self):
super(MainMenu, self).__init__("The Williams' Search Task")
self.screen = director.get_window_size()
ratio = self.screen[1] / self.screen[0]
self.select_sound = StaticSource(pyglet.resource.media('move.wav'))
self.font_title['font_name'] = 'Pipe Dream'
self.font_title['font_size'] = self.screen[0] / 18
self.font_title['color'] = (255, 255, 255, 255)
self.font_item['font_name'] = 'Pipe Dream',
self.font_item['color'] = (255, 255, 255, 255)
self.font_item['font_size'] = self.screen[1] / 16 * ratio
self.font_item_selected['font_name'] = 'Pipe Dream'
self.font_item_selected['color'] = (0, 0, 255, 255)
self.font_item_selected['font_size'] = self.screen[1] / 16 * ratio
self.menu_anchor_y = 'center'
self.menu_anchor_x = 'center'
self.items = OrderedDict()
self.items['mode'] = MultipleMenuItem('Mode: ', self.on_mode, director.settings['modes'], director.settings['modes'].index(director.settings['mode']))
self.items['player'] = MultipleMenuItem('Player: ', self.on_player, director.settings['players'], director.settings['players'].index(director.settings['player']))
self.items['start'] = MenuItem('Start', self.on_start)
self.items['options'] = MenuItem('Options', self.on_options)
self.items['quit'] = MenuItem('Quit', self.on_quit)
self.create_menu(self.items.values(), zoom_in(), zoom_out())
示例12: __init__
def __init__(self, **kw):
self.fields = OrderedDict(self.__class__.fields)
for k,v in kw.items():
if callable(v):
self.fields[k] = v(self.fields[k])
else:
self.fields[k] = v
示例13: Node
class Node(object):
def __init__(self, name):
self.name = name
self.attributes = OrderedDict()
self.children = []
self.parent = None
def __eq__(self, other):
return (type(other) == type(self) and
self.name == other.name and
dict(self.attributes) == dict(other.attributes) and
self.children == other.children)
def __ne__(self, other):
return not self == other
__gt__ = __lt__ = __ge__ = __le__ = not_implemented
__hash__ = None
def to_string(self):
attribute_string = "".join(' %s="%s"' % (key, value) for key, value in
self.attributes.items())
name = self.name
if not self.children:
return '<%s />' % (name + attribute_string)
children_string = "".join(node.to_string() for node in self.children)
return '<%s>%s</%s>' % (name + attribute_string, children_string, self.name)
# Hmmm...
__repr__ = to_string
示例14: __init__
def __init__(self, name, trackers, cls=Monitor):
self.name = name
self.count = 0
self.trackers = OrderedDict()
for n, getter in trackers:
mon = cls("%s: %s" % (name, n))
self.trackers[n] = (mon, getter)
示例15: __init__
def __init__(self):
super(OptionsMenu, self).__init__('Options')
self.screen = director.get_window_size()
ratio = self.screen[1] / self.screen[0]
self.font_title['font_size'] = self.screen[0] / 18
self.font_title['color'] = (255, 255, 255, 255)
self.font_item['color'] = (255, 255, 255, 255)
self.font_item['font_size'] = self.screen[1] / 16 * ratio
self.font_item_selected['color'] = (0, 0, 255, 255)
self.font_item_selected['font_size'] = self.screen[1] / 16 * ratio
self.items = OrderedDict()
self.speed_opts = ['SLOW','FAST']
self.level_opts = ['NONE','WEAK','MEDIUM','STRONG']
self.eye_opts = ['NONE','RIGHT','LEFT']
self.points_opts = ['2','5','9','13']
self.items['overlay'] = ToggleMenuItem('Debug Overlay:', self.on_overlay, director.settings['overlay'])
self.items['eyetracker'] = ToggleMenuItem('EyeTracker:', self.on_eyetracker, director.settings['eyetracker'])
self.items['eyetracker_ip'] = EntryMenuItem('EyeTracker IP:', self.on_eyetracker_ip, director.settings['eyetracker_ip'])
self.items['eyetracker_in_port'] = EntryMenuItem('EyeTracker In Port:', self.on_eyetracker_in_port, director.settings['eyetracker_in_port'])
self.items['eyetracker_out_port'] = EntryMenuItem('EyeTracker Out Port:', self.on_eyetracker_out_port, director.settings['eyetracker_out_port'])
self.items['calibration_points'] = MultipleMenuItem('Calibration Points:', self.on_cal_points, self.points_opts, self.points_opts.index(str(director.settings['calibration_points'])))
self.items['calibration_eye'] = MultipleMenuItem('Calibration Eye:', self.on_cal_eye, self.eye_opts, director.settings['calibration_eye'])
self.items['calibration_level'] = MultipleMenuItem('Calibration Check Level:', self.on_cal_level, self.level_opts, director.settings['calibration_level'])
self.items['calibration_speed'] = MultipleMenuItem('Calibration Speed:', self.on_cal_speed, self.speed_opts, director.settings['calibration_speed'])
self.items['calibration_auto'] = ToggleMenuItem('Calibration Auto-accept:', self.on_cal_auto, director.settings['calibration_auto'])
self.items['calibration_wait'] = ToggleMenuItem('Calibration Wait For Good:', self.on_cal_wait, director.settings['calibration_wait'])
self.items['calibration_random'] = ToggleMenuItem('Calibration Randomize:', self.on_cal_random, director.settings['calibration_random'])
self.create_menu(self.items.values(), zoom_in(), zoom_out())