本文整理汇总了Python中collections.Iterable方法的典型用法代码示例。如果您正苦于以下问题:Python collections.Iterable方法的具体用法?Python collections.Iterable怎么用?Python collections.Iterable使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类collections
的用法示例。
在下文中一共展示了collections.Iterable方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: validate_sections
# 需要导入模块: import collections [as 别名]
# 或者: from collections import Iterable [as 别名]
def validate_sections(self, list_sections):
"""
Validate a list of section names for availability.
@param list_sections: list of section names
@type list_sections: list of str
@return: None if all valid, otherwise list of invalid sections
@rtype: None | list[str]
"""
assert isinstance(list_sections, Iterable), "Invalid, not a list: '{}'".format(list_sections)
invalid_sections = []
for section in list_sections:
if not self._config.has_section(section):
invalid_sections.append(section)
if len(invalid_sections) > 0:
return invalid_sections
return None
示例2: default
# 需要导入模块: import collections [as 别名]
# 或者: from collections import Iterable [as 别名]
def default(self, obj):
if hasattr(obj, '__json__'):
return obj.__json__()
elif isinstance(obj, collections.Iterable):
return list(obj)
elif isinstance(obj, dt.datetime):
return obj.isoformat()
elif hasattr(obj, '__getitem__') and hasattr(obj, 'keys'):
return dict(obj)
elif hasattr(obj, '__dict__'):
return {member: getattr(obj, member)
for member in dir(obj)
if not member.startswith('_') and
not hasattr(getattr(obj, member), '__call__')}
return json.JSONEncoder.default(self, obj)
示例3: encode
# 需要导入模块: import collections [as 别名]
# 或者: from collections import Iterable [as 别名]
def encode(self, text):
"""Support batch or single str.
Args:
text (str or list of str): texts to convert.
Returns:
torch.IntTensor [length_0 + length_1 + ... length_{n - 1}]: encoded texts.
torch.IntTensor [n]: length of each text.
"""
if isinstance(text, str):
text = [
self.dict[char.lower() if self._ignore_case else char]
for char in text
]
length = [len(text)]
elif isinstance(text, collections.Iterable):
length = [len(s) for s in text]
text = ''.join(text)
text, _ = self.encode(text)
return (torch.IntTensor(text), torch.IntTensor(length))
示例4: changeScale
# 需要导入模块: import collections [as 别名]
# 或者: from collections import Iterable [as 别名]
def changeScale(self, img, size, interpolation=Image.BILINEAR):
if not _is_pil_image(img):
raise TypeError(
'img should be PIL Image. Got {}'.format(type(img)))
if not (isinstance(size, int) or (isinstance(size, collections.Iterable) and len(size) == 2)):
raise TypeError('Got inappropriate size arg: {}'.format(size))
if isinstance(size, int):
w, h = img.size
if (w <= h and w == size) or (h <= w and h == size):
return img
if w < h:
ow = size
oh = int(size * h / w)
return img.resize((ow, oh), interpolation)
else:
oh = size
ow = int(size * w / h)
return img.resize((ow, oh), interpolation)
else:
return img.resize(size[::-1], interpolation)
示例5: __init__
# 需要导入模块: import collections [as 别名]
# 或者: from collections import Iterable [as 别名]
def __init__(self, model_spec, **kwargs):
if isinstance(model_spec, (ModelMeta, string_type)):
self.model_classes = (model_spec,)
allow_subclasses = True
elif isinstance(model_spec, Iterable):
self.model_classes = tuple(model_spec)
allow_subclasses = False
else:
raise Exception("The first argument to PolyModelType.__init__() "
"must be a model or an iterable.")
self.claim_function = kwargs.pop("claim_function", None)
self.allow_subclasses = kwargs.pop("allow_subclasses", allow_subclasses)
CompoundType.__init__(self, **kwargs)
示例6: split_by
# 需要导入模块: import collections [as 别名]
# 或者: from collections import Iterable [as 别名]
def split_by(source, target, separator=None):
"""Split the source to multiple values by the separator"""
try:
if not source:
return []
elif isinstance(source, six.string_types) and separator:
values = source.split(separator)
return [{target: value.strip()} for value in values]
elif isinstance(source, six.string_types):
return [{target: source}]
elif isinstance(source, Iterable):
return [{target: value} for value in source]
else:
return [{target: source}]
except Exception as ex:
_logger.warning("split_by method encountered exception "
"source=%s message=%s cause=%s", source, ex,
traceback.format_exc())
return []
示例7: flatten_tuple_list
# 需要导入模块: import collections [as 别名]
# 或者: from collections import Iterable [as 别名]
def flatten_tuple_list(input_list):
"""Return a flattened generator from an input list of (x, y, z) tuples.
Usage:
input_list = [[(0, 0, 0)], [(10, 0, 0), (10, 10, 0)]]
print(list(flattenPointList(input_list)))
>> [(0, 0, 0), (10, 0, 0), (10, 10, 0)]
"""
for el in input_list:
if isinstance(el, collections.Iterable) \
and not isinstance(el, basestring) \
and (isinstance(el[0], collections.Iterable) or hasattr(el[0], 'X')):
for sub in flatten_tuple_list(el):
yield sub
else:
yield el
示例8: to_rad_string
# 需要导入模块: import collections [as 别名]
# 或者: from collections import Iterable [as 别名]
def to_rad_string(self):
"""Return formatted value for Radiance based on the type of descriptor."""
if self._value is None:
return ""
try:
if not isinstance(self._value, basestring) \
and isinstance(self._value, Iterable):
# tuple
return "-%s %s" % (self._name, " ".join(map(str, self._value)))
else:
if self._is_joined:
# joined strings such as -of
return "-%s%s" % (self._name, str(self._value))
else:
# numbers
return "-%s %s" % (self._name, str(self._value))
except TypeError:
raise ValueError("Failed to set the value to {}".format(self._value))
示例9: repr_list
# 需要导入模块: import collections [as 别名]
# 或者: from collections import Iterable [as 别名]
def repr_list(_list, indent):
"""Return a debug representation of a list or tuple."""
# pprint represents lists and tuples in one row if possible. We want one
# per row, so we iterate ourselves.
if _list is None:
return 'None'
if isinstance(_list, MutableSequence):
bm = '['
em = ']'
elif isinstance(_list, Iterable):
bm = '('
em = ')'
else:
raise TypeError("Object must be an iterable, but is a %s" %
type(_list))
ret = bm + '\n'
for value in _list:
ret += _indent('%r,\n' % value, 2)
ret += em
ret = repr_text(ret, indent=indent)
return ret.lstrip(' ')
示例10: is_incomplete_argument
# 需要导入模块: import collections [as 别名]
# 或者: from collections import Iterable [as 别名]
def is_incomplete_argument(current_params, cmd_param):
"""
:param current_params: the current params and values for this argument as already entered
:param cmd_param: the current command parameter
:return: whether or not the last argument is incomplete and corresponds to this cmd_param. In
other words whether or not the this cmd_param argument can still accept values
"""
if not isinstance(cmd_param, Argument):
return False
current_param_values = current_params[cmd_param.name]
if current_param_values is None:
return True
if cmd_param.nargs == -1:
return True
if isinstance(current_param_values, abc.Iterable) \
and cmd_param.nargs > 1 and len(current_param_values) < cmd_param.nargs:
return True
return False
示例11: _listlike_guard
# 需要导入模块: import collections [as 别名]
# 或者: from collections import Iterable [as 别名]
def _listlike_guard(obj, name, iterable_only=False, log_warning=True):
"""
We frequently require passed objects to support iteration or
containment expressions, but not be strings. (Of course, strings
support iteration and containment, but not usefully.) If the passed
object is a string, we'll wrap it in a tuple and return it. If it's
already an iterable, we'll return it as-is. Otherwise, we'll raise a
TypeError.
"""
required_type = (_Iterable,) if iterable_only else (_Container, _Iterable)
required_type_name = ' or '.join(t.__name__ for t in required_type)
if not isinstance(obj, required_type):
raise ValueError('{} must be of type {}'.format(name, required_type_name))
# at this point it is definitely the right type, but might be a string
if isinstance(obj, basestring):
if log_warning:
_logger.warning('{} passed as a string; should be list-like'.format(name))
return (obj,)
return obj
示例12: __init__
# 需要导入模块: import collections [as 别名]
# 或者: from collections import Iterable [as 别名]
def __init__(self, mapping=None):
"""Initialize a Catalog Builder.
Args:
mapping: An optional mapping (such as a dictionary) of items, or an
iterable series of 2-tuples containing keys and values.
Raises:
TypeError: If mapping is not None and is neither of mapping nor iterable type.
ValueError: If mapping is an iterable of tuples, and the tuples are not pairs.
"""
if mapping is None:
self._catalog = []
elif isinstance(mapping, Mapping):
self._catalog = list(mapping.items())
elif isinstance(mapping, Iterable):
self._catalog = []
for pair in mapping:
if len(pair) != 2:
raise ValueError("{!r} is not a pair. Catalogs can only be constructed "
"from iterable series of 2-tuples.")
self._catalog.append(pair)
else:
raise TypeError("Mapping must be either a mapping (e.g. dict), or an iterable "
"series of 2-tuples. {!r} does not qualify.")
示例13: __init__
# 需要导入模块: import collections [as 别名]
# 或者: from collections import Iterable [as 别名]
def __init__(self, size, interpolation='bilinear'):
assert isinstance(size, int) or (isinstance(size, collections.Iterable) and len(size) == 2)
self.size = size
self.interpolation = interpolation
示例14: log_invalid_sections
# 需要导入模块: import collections [as 别名]
# 或者: from collections import Iterable [as 别名]
def log_invalid_sections(self, list_sections):
"""
print out a list of invalid section names to log.
@param list_sections: list of section names
@type list_sections: list[str]
@return: None
@rtype: None
"""
assert isinstance(list_sections, Iterable), "Invalid, not a list: '{}'".format(list_sections)
for section in list_sections:
self._logger.warning("Invalid section '{}'".format(section))
示例15: __init__
# 需要导入模块: import collections [as 别名]
# 或者: from collections import Iterable [as 别名]
def __init__(self, size, interpolation=Image.BILINEAR):
assert isinstance(size, int) or (isinstance(size, collections.Iterable) and len(size) == 2)
self.size = size
self.interpolation = interpolation