當前位置: 首頁>>代碼示例>>Python>>正文


Python abc.Iterable方法代碼示例

本文整理匯總了Python中collections.abc.Iterable方法的典型用法代碼示例。如果您正苦於以下問題:Python abc.Iterable方法的具體用法?Python abc.Iterable怎麽用?Python abc.Iterable使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在collections.abc的用法示例。


在下文中一共展示了abc.Iterable方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: check_and_cast_args

# 需要導入模塊: from collections import abc [as 別名]
# 或者: from collections.abc import Iterable [as 別名]
def check_and_cast_args(args):
    """Check and cast arguments for the dependency tracer.

    Since autograd is expecting to compute derivatives, ints are not
    allowable as arguments. However, for our purposes, casting ints
    to floats will not affect dependency tracing.
    """
    # Currently this function only casts int into floats and raises
    # if the element is a string. This can be expanded to be more robust.
    def check_and_cast(arg):
        """Attempt to cast the arg to something traceable. Otherwise, error."""
        if isinstance(arg, str):
            raise ValueError(f"Cannot build causal graph for arg {arg} of type str")
        if isinstance(arg, int):
            arg = float(arg)
        return arg

    if isinstance(args, Iterable):
        return [check_and_cast(arg) for arg in args]
    return check_and_cast(args) 
開發者ID:zykls,項目名稱:whynot,代碼行數:22,代碼來源:causal_graphs.py

示例2: is_incomplete_argument

# 需要導入模塊: from collections import abc [as 別名]
# 或者: from collections.abc 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

示例3: handle_emitter

# 需要導入模塊: from collections import abc [as 別名]
# 或者: from collections.abc import Iterable [as 別名]
def handle_emitter(self):
        """
        This emitter uses the user-implemented create_message() method to get
        whatever data the robot gathered, convert it to a string if needed and
        then use the emitter to send the data in a string utf-8 encoding to the
        supervisor.
        """
        data = self.create_message()

        assert isinstance(data,
                          Iterable), "The action object should be Iterable"

        string_message = ""
        # message can either be a list that needs to be converted in a string
        # or a straight-up string
        if type(data) is list:
            string_message = ",".join(map(str, data))
        elif type(data) is str:
            string_message = data
        else:
            raise TypeError(
                "message must be either a comma-separated string or a 1D list")

        string_message = string_message.encode("utf-8")
        self.emitter.send(string_message) 
開發者ID:aidudezzz,項目名稱:deepbots,代碼行數:27,代碼來源:robot_emitter_receiver_csv.py

示例4: _check_if_func_available

# 需要導入模塊: from collections import abc [as 別名]
# 或者: from collections.abc import Iterable [as 別名]
def _check_if_func_available(func):
    to_check = []
    if isinstance(func, list):
        to_check.extend(func)
    elif isinstance(func, dict):
        for f in func.values():
            if isinstance(f, Iterable) and not isinstance(f, str):
                to_check.extend(f)
            else:
                to_check.append(f)
    else:
        to_check.append(func)

    for f in to_check:
        if f not in _available_aggregation_functions:
            return False
    return True 
開發者ID:mars-project,項目名稱:mars,代碼行數:19,代碼來源:aggregation.py

示例5: __call__

# 需要導入模塊: from collections import abc [as 別名]
# 或者: from collections.abc import Iterable [as 別名]
def __call__(self, groupby):
        indexed = groupby.op.build_mock_groupby()[self.selection]

        if isinstance(indexed, pd_groupby.SeriesGroupBy):
            self.output_types = [OutputType.series_groupby]
            params = dict(shape=(groupby.shape[0],), name=self.selection,
                          dtype=groupby.dtypes[self.selection],
                          index_value=groupby.index_value,
                          key_dtypes=groupby.key_dtypes)
        else:
            self.output_types = [OutputType.dataframe_groupby]

            if isinstance(self.selection, Iterable) and not isinstance(self.selection, str):
                item_list = list(self.selection)
            else:
                item_list = [self.selection]

            params = groupby.params.copy()
            params['dtypes'] = new_dtypes = groupby.dtypes[item_list]
            params['selection'] = self.selection
            params['shape'] = (groupby.shape[0], len(item_list))
            params['columns_value'] = parse_index(new_dtypes.index, store_data=True)

        return self.new_tileable([groupby], **params) 
開發者ID:mars-project,項目名稱:mars,代碼行數:26,代碼來源:getitem.py

示例6: df_groupby_getitem

# 需要導入模塊: from collections import abc [as 別名]
# 或者: from collections.abc import Iterable [as 別名]
def df_groupby_getitem(df_groupby, item):
    try:
        hash(item)
        hashable = True
    except TypeError:
        hashable = False

    if hashable and item in df_groupby.dtypes:
        output_types = [OutputType.series_groupby]
    elif isinstance(item, Iterable) and all(it in df_groupby.dtypes for it in item):
        output_types = [OutputType.dataframe_groupby]
    else:
        raise NameError('Cannot slice groupby with %r' % item)

    if df_groupby.selection:
        raise IndexError('Column(s) %r already selected' % df_groupby.selection)

    op = GroupByIndex(selection=item, output_types=output_types)
    return op(df_groupby) 
開發者ID:mars-project,項目名稱:mars,代碼行數:21,代碼來源:getitem.py

示例7: _is_funcs_agg

# 需要導入模塊: from collections import abc [as 別名]
# 或者: from collections.abc import Iterable [as 別名]
def _is_funcs_agg(func):
    to_check = []
    if isinstance(func, list):
        to_check.extend(func)
    elif isinstance(func, dict):
        for f in func.values():
            if isinstance(f, Iterable) and not isinstance(f, str):
                to_check.extend(f)
            else:
                to_check.append(f)
    else:
        to_check.append(func)

    for f in to_check:
        if f not in _builtin_aggregation_functions:
            return False
    return True 
開發者ID:mars-project,項目名稱:mars,代碼行數:19,代碼來源:aggregation.py

示例8: _get_squeeze_shape

# 需要導入模塊: from collections import abc [as 別名]
# 或者: from collections.abc import Iterable [as 別名]
def _get_squeeze_shape(shape, axis):
    if axis is not None:
        if isinstance(axis, Iterable):
            axis = tuple(axis)
        else:
            axis = (axis,)

        for ax in axis:
            if shape[ax] != 1:
                raise ValueError('cannot select an axis to squeeze out '
                                 'which has size not equal to one')
        shape = tuple(s for i, s in enumerate(shape) if i not in axis)
    else:
        axis = tuple(i for i, s in enumerate(shape) if s == 1)
        shape = tuple(s for s in shape if s != 1)

    return shape, axis 
開發者ID:mars-project,項目名稱:mars,代碼行數:19,代碼來源:squeeze.py

示例9: base_equal

# 需要導入模塊: from collections import abc [as 別名]
# 或者: from collections.abc import Iterable [as 別名]
def base_equal(self, ob1, ob2):
        if type(ob1) != type(ob2):
            return False

        def cmp(obj1, obj2):
            if isinstance(obj1, np.ndarray):
                return np.array_equal(obj1, obj2)
            elif isinstance(obj1, Iterable) and \
                    not isinstance(obj1, str) and \
                    isinstance(obj2, Iterable) and \
                    not isinstance(obj2, str):
                return all(cmp(it1, it2) for it1, it2 in itertools.zip_longest(obj1, obj2))
            elif hasattr(obj1, 'key') and hasattr(obj2, 'key'):
                return obj1.key == obj2.key
            elif isinstance(obj1, ReferenceType) and isinstance(obj2, ReferenceType):
                return cmp(obj1(), obj2())
            else:
                return obj1 == obj2

        for slot in ob1.__slots__:
            if not cmp(getattr(ob1, slot, None), getattr(ob2, slot, None)):
                return False

        return True 
開發者ID:mars-project,項目名稱:mars,代碼行數:26,代碼來源:core.py

示例10: cast_tensor_type

# 需要導入模塊: from collections import abc [as 別名]
# 或者: from collections.abc import Iterable [as 別名]
def cast_tensor_type(inputs, src_type, dst_type):
    if isinstance(inputs, torch.Tensor):
        return inputs.to(dst_type)
    elif isinstance(inputs, str):
        return inputs
    elif isinstance(inputs, np.ndarray):
        return inputs
    elif isinstance(inputs, abc.Mapping):
        return type(inputs)({
            k: cast_tensor_type(v, src_type, dst_type)
            for k, v in inputs.items()
        })
    elif isinstance(inputs, abc.Iterable):
        return type(inputs)(
            cast_tensor_type(item, src_type, dst_type) for item in inputs)
    else:
        return inputs 
開發者ID:DeepMotionAIResearch,項目名稱:DenseMatchingBenchmark,代碼行數:19,代碼來源:utils.py

示例11: group_as_dict

# 需要導入模塊: from collections import abc [as 別名]
# 或者: from collections.abc import Iterable [as 別名]
def group_as_dict(pairs):
    """Combines a list of key-value pairs to a dictionary of keys and value lists.

    Does not require the pairs to be sorted by keys.

    Parameters
    ----------
    pairs : iterable
        Iterable of key-value pairs

    Returns
    -------
    dict
        The dictionary of keys and value lists.
    """
    dic = defaultdict(list)
    for key, value in pairs:
        dic[key].append(value)
    return dic 
開發者ID:dmlc,項目名稱:dgl,代碼行數:21,代碼來源:utils.py

示例12: files

# 需要導入模塊: from collections import abc [as 別名]
# 或者: from collections.abc import Iterable [as 別名]
def files(self, files):
        if not isinstance(files, utils.Iterable):
            raise ValueError(f'Not an Iterable: {files}')
        for f in files:
            if not isinstance(f, utils.File):
                raise ValueError(f'Not a File object: {f}')
            elif f.is_absolute():
                raise error.PathError(f, msg='Not a relative path')

        if not files:
            self._set_files(files=())
        else:
            # os.path.commonpath() returns '' if there is no common path and
            # raises ValueError if there are absolute and relative paths.
            try:
                basepath = os.path.commonpath(files)
            except ValueError:
                basepath = ''
            if basepath == '':
                raise error.CommonPathError(files)
            self._set_files(files, pathlib.Path(basepath)) 
開發者ID:rndusr,項目名稱:torf,代碼行數:23,代碼來源:_torrent.py

示例13: filepaths

# 需要導入模塊: from collections import abc [as 別名]
# 或者: from collections.abc import Iterable [as 別名]
def filepaths(self, filepaths):
        if not isinstance(filepaths, utils.Iterable):
            raise ValueError(f'Not an Iterable: {filepaths}')

        filepaths = utils.Filepaths(filepaths)  # Resolve directories
        if not filepaths:
            self._set_files(files=())
        else:
            # Make all paths absolute so we can find the common path.  Do not
            # resolve symlinks so the user isn't confronted with unexpected
            # paths in case of an error.
            cwd = pathlib.Path.cwd()
            filepaths_abs = tuple(fp if fp.is_absolute() else cwd / fp
                                  for fp in filepaths)
            try:
                basepath = pathlib.Path(os.path.commonpath(filepaths_abs))
            except ValueError:
                raise error.CommonPathError(filepaths)
            filepaths = tuple(utils.File(fp, size=utils.real_size(fp))
                              for fp in filepaths)
            self._set_files(filepaths, basepath) 
開發者ID:rndusr,項目名稱:torf,代碼行數:23,代碼來源:_torrent.py

示例14: role

# 需要導入模塊: from collections import abc [as 別名]
# 或者: from collections.abc import Iterable [as 別名]
def role(self):
        """Return Jira role information.

        :return: List of current user roles
        :rtype: Iterable

        """
        # https://developer.atlassian.com/cloud/jira/platform/rest/v3/?utm_source=%2Fcloud%2Fjira%2Fplatform%2Frest%2F&utm_medium=302#api-rest-api-3-role-get

        url = self._options["server"] + "/rest/api/latest/role"

        r = self._session.get(url)
        return json_loads(r)

    # Experimental
    # Experimental support for iDalko Grid, expect API to change as it's using private APIs currently
    # https://support.idalko.com/browse/IGRID-1017 
開發者ID:pycontribs,項目名稱:jira,代碼行數:19,代碼來源:client.py

示例15: iter_cast

# 需要導入模塊: from collections import abc [as 別名]
# 或者: from collections.abc import Iterable [as 別名]
def iter_cast(inputs, dst_type, return_type=None):
    """Cast elements of an iterable object into some type.

    Args:
        inputs (Iterable): The input object.
        dst_type (type): Destination type.
        return_type (type, optional): If specified, the output object will be
            converted to this type, otherwise an iterator.

    Returns:
        iterator or specified type: The converted object.
    """
    if not isinstance(inputs, collections_abc.Iterable):
        raise TypeError('inputs must be an iterable object')
    if not isinstance(dst_type, type):
        raise TypeError('"dst_type" must be a valid type')

    out_iterable = six.moves.map(dst_type, inputs)

    if return_type is None:
        return out_iterable
    else:
        return return_type(out_iterable) 
開發者ID:Media-Smart,項目名稱:vedaseg,代碼行數:25,代碼來源:misc.py


注:本文中的collections.abc.Iterable方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。