当前位置: 首页>>代码示例>>Python>>正文


Python collections.Iterable方法代码示例

本文整理汇总了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 
开发者ID:CAMI-challenge,项目名称:CAMISIM,代码行数:20,代码来源:configparserwrapper.py

示例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) 
开发者ID:taspinar,项目名称:twitterscraper,代码行数:18,代码来源:main.py

示例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)) 
开发者ID:zzzDavid,项目名称:ICDAR-2019-SROIE,代码行数:23,代码来源:utils.py

示例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) 
开发者ID:JunjH,项目名称:Visualizing-CNNs-for-monocular-depth-estimation,代码行数:24,代码来源:nyu_transform.py

示例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) 
开发者ID:remg427,项目名称:misp42splunk,代码行数:18,代码来源:compound.py

示例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 [] 
开发者ID:remg427,项目名称:misp42splunk,代码行数:21,代码来源:ext.py

示例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 
开发者ID:ladybug-tools,项目名称:honeybee,代码行数:19,代码来源:dataoperation.py

示例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)) 
开发者ID:ladybug-tools,项目名称:honeybee,代码行数:22,代码来源:datatype.py

示例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(' ') 
开发者ID:zhmcclient,项目名称:python-zhmcclient,代码行数:23,代码来源:_utils.py

示例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 
开发者ID:Frank-qlu,项目名称:recruit,代码行数:20,代码来源:_bashcomplete.py

示例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 
开发者ID:cloudendpoints,项目名称:endpoints-python,代码行数:22,代码来源:users_id_token.py

示例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.") 
开发者ID:sixty-north,项目名称:segpy,代码行数:27,代码来源:catalog.py

示例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 
开发者ID:jthsieh,项目名称:DDPAE-video-prediction,代码行数:6,代码来源:video_transforms.py

示例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)) 
开发者ID:CAMI-challenge,项目名称:CAMISIM,代码行数:15,代码来源:configparserwrapper.py

示例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 
开发者ID:awslabs,项目名称:dynamic-training-with-apache-mxnet-on-aws,代码行数:6,代码来源:utils.py


注:本文中的collections.Iterable方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。