本文整理汇总了Python中ordered_set.OrderedSet方法的典型用法代码示例。如果您正苦于以下问题:Python ordered_set.OrderedSet方法的具体用法?Python ordered_set.OrderedSet怎么用?Python ordered_set.OrderedSet使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类ordered_set
的用法示例。
在下文中一共展示了ordered_set.OrderedSet方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: fit
# 需要导入模块: import ordered_set [as 别名]
# 或者: from ordered_set import OrderedSet [as 别名]
def fit(self, array):
'''
:param array: list or np array
:return: None
'''
unique_elements = OrderedSet(array)
# unique_elements = sorted(unique_elements)
# print(DUMMY_ITEM in unique_elements)
# print('-1' in unique_elements)
self.n_elements = 0
self.f_dict = {}
self.r_dict = {}
for e in unique_elements:
self.f_dict[e] = self.n_elements
self.r_dict[self.n_elements] = e
self.n_elements += 1
示例2: lpop
# 需要导入模块: import ordered_set [as 别名]
# 或者: from ordered_set import OrderedSet [as 别名]
def lpop(self):
"""
Remove and return the first element from the set.
Raises KeyError if the set is empty.
Example:
>>> oset = OrderedSet([1, 2, 3])
>>> oset.lpop()
1
"""
if not self.items:
raise KeyError('lpop from an empty set')
elem = self.items[0]
del self.items[0]
del self.map[elem]
return elem
示例3: __init__
# 需要导入模块: import ordered_set [as 别名]
# 或者: from ordered_set import OrderedSet [as 别名]
def __init__(self, *args, timeout=None, **kwargs) -> None:
super().__init__(*args, **kwargs)
# Store timeout
self.timeout = timeout
# Override server protocols set
self.protocols = ordered_set.OrderedSet()
# Most recent connection closed future
self._most_recent_connection_closed_future = asyncio.Future(loop=self._loop)
示例4: get_ignore_types_in_groups
# 需要导入模块: import ordered_set [as 别名]
# 或者: from ordered_set import OrderedSet [as 别名]
def get_ignore_types_in_groups(self, ignore_type_in_groups,
ignore_string_type_changes,
ignore_numeric_type_changes,
ignore_type_subclasses):
if ignore_type_in_groups:
if isinstance(ignore_type_in_groups[0], type):
ignore_type_in_groups = [ignore_type_in_groups]
else:
ignore_type_in_groups = []
result = []
for item_group in ignore_type_in_groups:
new_item_group = OrderedSet()
for item in item_group:
item = type(item) if item is None or not isinstance(item, type) else item
new_item_group.add(item)
result.append(new_item_group)
ignore_type_in_groups = result
if ignore_string_type_changes and self.strings not in ignore_type_in_groups:
ignore_type_in_groups.append(OrderedSet(self.strings))
if ignore_numeric_type_changes and self.numbers not in ignore_type_in_groups:
ignore_type_in_groups.append(OrderedSet(self.numbers))
if ignore_type_subclasses:
ignore_type_in_groups = list(map(tuple, ignore_type_in_groups))
return ignore_type_in_groups
示例5: __init__
# 需要导入模块: import ordered_set [as 别名]
# 或者: from ordered_set import OrderedSet [as 别名]
def __init__(self, key, report_type, value, freq_node, pre, nxt):
self.key = key
if report_type:
self.content = defaultdict(OrderedSet)
self.content[report_type].add(value)
else:
self.content = value
self.freq_node = freq_node
self.pre = pre # previous CacheNode
self.nxt = nxt # next CacheNode
示例6: __init__
# 需要导入模块: import ordered_set [as 别名]
# 或者: from ordered_set import OrderedSet [as 别名]
def __init__(self,
obj,
item,
exclude_paths=OrderedSet(),
exclude_regex_paths=OrderedSet(),
exclude_types=OrderedSet(),
verbose_level=1,
case_sensitive=False,
match_string=False,
**kwargs):
if kwargs:
raise ValueError((
"The following parameter(s) are not valid: %s\n"
"The valid parameters are obj, item, exclude_paths, exclude_types,\n"
"case_sensitive, match_string and verbose_level."
) % ', '.join(kwargs.keys()))
self.obj = obj
self.case_sensitive = case_sensitive if isinstance(item, strings) else True
item = item if self.case_sensitive else item.lower()
self.exclude_paths = OrderedSet(exclude_paths)
self.exclude_regex_paths = [re.compile(exclude_regex_path) for exclude_regex_path in exclude_regex_paths]
self.exclude_types = OrderedSet(exclude_types)
self.exclude_types_tuple = tuple(
exclude_types) # we need tuple for checking isinstance
self.verbose_level = verbose_level
self.update(
matched_paths=self.__set_or_dict(),
matched_values=self.__set_or_dict(),
unprocessed=[])
# Cases where user wants to match exact string item
self.match_string = match_string
self.__search(obj, item, parents_ids=frozenset({id(obj)}))
empty_keys = [k for k, v in self.items() if not v]
for k in empty_keys:
del self[k]
示例7: __set_or_dict
# 需要导入模块: import ordered_set [as 别名]
# 或者: from ordered_set import OrderedSet [as 别名]
def __set_or_dict(self):
return dict_() if self.verbose_level >= 2 else OrderedSet()
示例8: __init__
# 需要导入模块: import ordered_set [as 别名]
# 或者: from ordered_set import OrderedSet [as 别名]
def __init__(self, items=None):
self._set = OrderedSet()
self._hashes = dict_()
self._hash_to_objects = dict_()
if items:
for item in items:
self.add(item)
示例9: test_serialize
# 需要导入模块: import ordered_set [as 别名]
# 或者: from ordered_set import OrderedSet [as 别名]
def test_serialize(self):
obj = [1, 2, 3, None, {10: 11E2}, frozenset(['a', 'c']), OrderedSet([2, 1]),
datetime.datetime.utcnow(), datetime.time(11), Decimal('11.2'), 123.11]
serialized = pickle_dump(obj)
loaded = pickle_load(serialized)
assert obj == loaded
示例10: check_type
# 需要导入模块: import ordered_set [as 别名]
# 或者: from ordered_set import OrderedSet [as 别名]
def check_type(value, ty, value_name="value"):
"""
Verify that the given value has the given type.
value - the value to check
ty - the type to check for, or None to do no checking
(for example, if types come from Python type annotations, and
the Python formal variable does not have a type annotation)
value_name - the variable or expression that evaluates to `value`;
printed in diagnostic messages
The type ty can be:
str, int, float, or bytes - value must have this type
[ty] - value must be a list of ty
{k:v} - value must be a dict with keys of type k and values of type v
"""
if ty is None:
pass
elif type(ty) is tuple:
assert isinstance(value, tuple), "{} has type {}, not {}".format(value_name, type(value).__name__, "tuple")
assert len(value) == len(ty), "{} has {} entries, not {}".format(value_name, len(value), len(ty))
for v, t, i in zip(value, ty, range(len(value))):
check_type(v, t, "{}[{}]".format(value_name, i))
elif type(ty) is list:
assert isinstance(value, list), "{} has type {}, not {}".format(value_name, type(value).__name__, "list")
for i in range(len(value)):
check_type(value[i], ty[0], "{}[{}]".format(value_name, i))
elif type(ty) is dict:
assert isinstance(value, dict), "{} has type {}, not {}".format(value_name, type(value).__name__, "dict")
((kt, vt),) = ty.items()
for k, v in value.items():
check_type(k, kt, value_name)
check_type(v, vt, "{}[{}]".format(value_name, k))
elif type(ty) is set:
assert isinstance(value, set) or isinstance(value, OrderedSet), "{} has type {}, not {}".format(value_name, type(value).__name__, "set")
subty, = ty
for x in value:
check_type(x, subty, "{} in {}".format(x, value_name))
else:
assert isinstance(value, ty), "{} has type {}, not {}".format(value_name, type(value).__name__, ty.__name__)
示例11: unique
# 需要导入模块: import ordered_set [as 别名]
# 或者: from ordered_set import OrderedSet [as 别名]
def unique(iter):
"""
Yields a stream of deduplicated elements.
Elements are returned in the same order as the input iterator.
"""
yield from OrderedSet(iter)
示例12: __new__
# 需要导入模块: import ordered_set [as 别名]
# 或者: from ordered_set import OrderedSet [as 别名]
def __new__(cls):
# yamlizable does not call __init__, so attributes that are not defined above
# need to be initialized here
self = yamlize.Object.__new__(cls)
self.assemblies = {}
self._prepped = False
self._assembliesBySpecifier = {}
self.allNuclidesInProblem = (
ordered_set.OrderedSet()
) # Better for performance since these are used for lookups
self.activeNuclides = ordered_set.OrderedSet()
self.inertNuclides = ordered_set.OrderedSet()
self.elementsToExpand = []
return self
示例13: __init__
# 需要导入模块: import ordered_set [as 别名]
# 或者: from ordered_set import OrderedSet [as 别名]
def __init__(self, meta_train=False, meta_val=False, meta_test=False,
meta_split=None, class_augmentations=None):
if meta_train + meta_val + meta_test == 0:
if meta_split is None:
raise ValueError('The meta-split is undefined. Use either the '
'argument `meta_train=True` (or `meta_val`/`meta_test`), or '
'the argument `meta_split="train"` (or "val"/"test").')
elif meta_split not in ['train', 'val', 'test']:
raise ValueError('Unknown meta-split name `{0}`. The meta-split '
'must be in [`train`, `val`, `test`].'.format(meta_split))
meta_train = (meta_split == 'train')
meta_val = (meta_split == 'val')
meta_test = (meta_split == 'test')
elif meta_train + meta_val + meta_test > 1:
raise ValueError('Multiple arguments among `meta_train`, `meta_val` '
'and `meta_test` are set to `True`. Exactly one must be set to '
'`True`.')
self.meta_train = meta_train
self.meta_val = meta_val
self.meta_test = meta_test
self._meta_split = meta_split
if class_augmentations is not None:
if not isinstance(class_augmentations, list):
raise TypeError('Unknown type for `class_augmentations`. '
'Expected `list`, got `{0}`.'.format(type(class_augmentations)))
unique_augmentations = OrderedSet()
for augmentations in class_augmentations:
for transform in augmentations:
if transform in unique_augmentations:
warnings.warn('The class augmentation `{0}` already '
'exists in the list of class augmentations (`{1}`). '
'To avoid any duplicate, this transformation is '
'ignored.'.format(transform, repr(transform)),
UserWarning, stacklevel=2)
unique_augmentations.add(transform)
class_augmentations = list(unique_augmentations)
else:
class_augmentations = []
self.class_augmentations = class_augmentations
示例14: test_class_splitter_for_fold_overlaps
# 需要导入模块: import ordered_set [as 别名]
# 或者: from ordered_set import OrderedSet [as 别名]
def test_class_splitter_for_fold_overlaps():
class DemoTask(Task):
def __init__(self):
super(DemoTask, self).__init__(index=0, num_classes=None)
self._inputs = np.arange(10)
def __len__(self):
return len(self._inputs)
def __getitem__(self, index):
return self._inputs[index]
splitter = ClassSplitter(shuffle=True, num_train_per_class=5, num_test_per_class=5)
task = DemoTask()
all_train_samples = list()
all_test_samples = list()
# split task ten times into train and test
for i in range(10):
tasks_split = splitter(task)
train_task = tasks_split["train"]
test_task = tasks_split["test"]
train_samples = set([train_task[i] for i in range(len(train_task))])
test_samples = set([test_task[i] for i in range(len(train_task))])
# no overlap between train and test splits at single split
assert len(train_samples.intersection(test_samples)) == 0
all_train_samples.append(train_samples)
all_train_samples.append(train_samples)
# gather unique samples from multiple splits
samples_in_all_train_splits = OrderedSet().union(*all_train_samples)
samples_in_all_test_splits = OrderedSet().union(*all_test_samples)
# no overlap between train and test splits at multiple splits
assert len(samples_in_all_test_splits.intersection(samples_in_all_train_splits)) == 0
示例15: _expand_sample_usage
# 需要导入模块: import ordered_set [as 别名]
# 或者: from ordered_set import OrderedSet [as 别名]
def _expand_sample_usage(meta_dataset, all_allowed_samples, additional_samples):
expanded_metadataset = {}
all_samples_of_metadataset = OrderedSet()
for key, value in meta_dataset.items():
all_samples_of_metadataset.update(value)
all_samples_of_metadataset.update(additional_samples)
used_additional_samples = OrderedSet()
for key in meta_dataset.keys():
allowed_samples = set(all_allowed_samples[key])
intersection = allowed_samples.intersection(all_samples_of_metadataset)
expanded_metadataset[key] = list(intersection)
used_additional_samples = additional_samples.intersection(intersection)
return expanded_metadataset, used_additional_samples