Python itertools.starmap() Examples

The following are 30 code examples for showing how to use itertools.starmap(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.

You may check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module itertools , or try the search function .

Example 1
Project: jawfish   Author: war-and-code   File: pool.py    License: MIT License 6 votes vote down vote up
def _map_async(self, func, iterable, mapper, chunksize=None, callback=None,
            error_callback=None):
        '''
        Helper function to implement map, starmap and their async counterparts.
        '''
        if self._state != RUN:
            raise ValueError("Pool not running")
        if not hasattr(iterable, '__len__'):
            iterable = list(iterable)

        if chunksize is None:
            chunksize, extra = divmod(len(iterable), len(self._pool) * 4)
            if extra:
                chunksize += 1
        if len(iterable) == 0:
            chunksize = 0

        task_batches = Pool._get_tasks(func, iterable, chunksize)
        result = MapResult(self._cache, chunksize, len(iterable), callback,
                           error_callback=error_callback)
        self._taskqueue.put((((result._job, i, mapper, (x,), {})
                              for i, x in enumerate(task_batches)), None))
        return result 
Example 2
Project: verge3d-blender-addon   Author: Soft8Soft   File: misc.py    License: GNU General Public License v3.0 6 votes vote down vote up
def elements(self):
        '''Iterator over elements repeating each as many times as its count.

        >>> c = Counter('ABCABC')
        >>> sorted(c.elements())
        ['A', 'A', 'B', 'B', 'C', 'C']

        # Knuth's example for prime factors of 1836:  2**2 * 3**3 * 17**1
        >>> prime_factors = Counter({2: 2, 3: 3, 17: 1})
        >>> product = 1
        >>> for factor in prime_factors.elements():     # loop over factors
        ...     product *= factor                       # and multiply them
        >>> product
        1836

        Note, if an element's count has been set to zero or is a negative
        number, elements() will ignore it.

        '''
        # Emulate Bag.do from Smalltalk and Multiset.begin from C++.
        return _chain.from_iterable(_starmap(_repeat, self.items()))

    # Override dict methods where necessary 
Example 3
Project: misp42splunk   Author: remg427   File: misc.py    License: GNU Lesser General Public License v3.0 6 votes vote down vote up
def elements(self):
        '''Iterator over elements repeating each as many times as its count.

        >>> c = Counter('ABCABC')
        >>> sorted(c.elements())
        ['A', 'A', 'B', 'B', 'C', 'C']

        # Knuth's example for prime factors of 1836:  2**2 * 3**3 * 17**1
        >>> prime_factors = Counter({2: 2, 3: 3, 17: 1})
        >>> product = 1
        >>> for factor in prime_factors.elements():     # loop over factors
        ...     product *= factor                       # and multiply them
        >>> product
        1836

        Note, if an element's count has been set to zero or is a negative
        number, elements() will ignore it.

        '''
        # Emulate Bag.do from Smalltalk and Multiset.begin from C++.
        return _chain.from_iterable(_starmap(_repeat, self.items()))

    # Override dict methods where necessary 
Example 4
Project: misp42splunk   Author: remg427   File: misc.py    License: GNU Lesser General Public License v3.0 6 votes vote down vote up
def elements(self):
        '''Iterator over elements repeating each as many times as its count.

        >>> c = Counter('ABCABC')
        >>> sorted(c.elements())
        ['A', 'A', 'B', 'B', 'C', 'C']

        # Knuth's example for prime factors of 1836:  2**2 * 3**3 * 17**1
        >>> prime_factors = Counter({2: 2, 3: 3, 17: 1})
        >>> product = 1
        >>> for factor in prime_factors.elements():     # loop over factors
        ...     product *= factor                       # and multiply them
        >>> product
        1836

        Note, if an element's count has been set to zero or is a negative
        number, elements() will ignore it.

        '''
        # Emulate Bag.do from Smalltalk and Multiset.begin from C++.
        return _chain.from_iterable(_starmap(_repeat, self.items()))

    # Override dict methods where necessary 
Example 5
Project: tsinfer   Author: tskit-dev   File: formats.py    License: GNU General Public License v3.0 6 votes vote down vote up
def individuals_equal(self, other):
        return (
            self.num_individuals == other.num_individuals
            and np.allclose(
                self.individuals_time[:], other.individuals_time[:], equal_nan=True
            )
            and all(
                itertools.starmap(
                    np.array_equal,
                    zip(self.individuals_metadata[:], other.individuals_metadata[:]),
                )
            )
            and all(
                itertools.starmap(
                    np.array_equal,
                    zip(self.individuals_location[:], other.individuals_location[:]),
                )
            )
        ) 
Example 6
Project: tsinfer   Author: tskit-dev   File: formats.py    License: GNU General Public License v3.0 6 votes vote down vote up
def sites_equal(self, other):
        return (
            self.num_sites == other.num_sites
            and self.num_inference_sites == other.num_inference_sites
            and np.all(self.sites_position[:] == other.sites_position[:])
            and np.all(self.sites_inference[:] == other.sites_inference[:])
            and np.all(self.sites_genotypes[:] == other.sites_genotypes[:])
            and np.allclose(self.sites_time[:], other.sites_time[:], equal_nan=True)
            and all(
                itertools.starmap(
                    np.array_equal, zip(self.sites_metadata[:], other.sites_metadata[:])
                )
            )
            and all(
                itertools.starmap(
                    np.array_equal, zip(self.sites_alleles[:], other.sites_alleles[:])
                )
            )
        ) 
Example 7
Project: meddle   Author: glmcdona   File: collections.py    License: MIT License 6 votes vote down vote up
def elements(self):
        '''Iterator over elements repeating each as many times as its count.

        >>> c = Counter('ABCABC')
        >>> sorted(c.elements())
        ['A', 'A', 'B', 'B', 'C', 'C']

        # Knuth's example for prime factors of 1836:  2**2 * 3**3 * 17**1
        >>> prime_factors = Counter({2: 2, 3: 3, 17: 1})
        >>> product = 1
        >>> for factor in prime_factors.elements():     # loop over factors
        ...     product *= factor                       # and multiply them
        >>> product
        1836

        Note, if an element's count has been set to zero or is a negative
        number, elements() will ignore it.

        '''
        # Emulate Bag.do from Smalltalk and Multiset.begin from C++.
        return _chain.from_iterable(_starmap(_repeat, self.iteritems()))

    # Override dict methods where necessary 
Example 8
Project: ironpython2   Author: IronLanguages   File: collections.py    License: Apache License 2.0 6 votes vote down vote up
def elements(self):
        '''Iterator over elements repeating each as many times as its count.

        >>> c = Counter('ABCABC')
        >>> sorted(c.elements())
        ['A', 'A', 'B', 'B', 'C', 'C']

        # Knuth's example for prime factors of 1836:  2**2 * 3**3 * 17**1
        >>> prime_factors = Counter({2: 2, 3: 3, 17: 1})
        >>> product = 1
        >>> for factor in prime_factors.elements():     # loop over factors
        ...     product *= factor                       # and multiply them
        >>> product
        1836

        Note, if an element's count has been set to zero or is a negative
        number, elements() will ignore it.

        '''
        # Emulate Bag.do from Smalltalk and Multiset.begin from C++.
        return _chain.from_iterable(_starmap(_repeat, self.iteritems()))

    # Override dict methods where necessary 
Example 9
Project: kobo-predict   Author: awemulya   File: __init__.py    License: BSD 2-Clause "Simplified" License 6 votes vote down vote up
def elements(self):
        '''Iterator over elements repeating each as many times as its count.

        >>> c = Counter('ABCABC')
        >>> sorted(c.elements())
        ['A', 'A', 'B', 'B', 'C', 'C']

        # Knuth's example for prime factors of 1836:  2**2 * 3**3 * 17**1
        >>> prime_factors = Counter({2: 2, 3: 3, 17: 1})
        >>> product = 1
        >>> for factor in prime_factors.elements():     # loop over factors
        ...     product *= factor                       # and multiply them
        >>> product
        1836

        Note, if an element's count has been set to zero or is a negative
        number, elements() will ignore it.

        '''
        # Emulate Bag.do from Smalltalk and Multiset.begin from C++.
        return _chain.from_iterable(_starmap(_repeat, self.items()))

    # Override dict methods where necessary 
Example 10
Project: vnpy_crypto   Author: birforce   File: test_operators.py    License: MIT License 6 votes vote down vote up
def test_timedelta64_equal_timedelta_supported_ops(self, op):
        ser = Series([Timestamp('20130301'), Timestamp('20130228 23:00:00'),
                      Timestamp('20130228 22:00:00'),
                      Timestamp('20130228 21:00:00')])

        intervals = 'D', 'h', 'm', 's', 'us'

        # TODO: unused
        # npy16_mappings = {'D': 24 * 60 * 60 * 1000000,
        #                   'h': 60 * 60 * 1000000,
        #                   'm': 60 * 1000000,
        #                   's': 1000000,
        #                   'us': 1}

        def timedelta64(*args):
            return sum(starmap(np.timedelta64, zip(args, intervals)))

        for d, h, m, s, us in product(*([range(2)] * 5)):
            nptd = timedelta64(d, h, m, s, us)
            pytd = timedelta(days=d, hours=h, minutes=m, seconds=s,
                             microseconds=us)
            lhs = op(ser, nptd)
            rhs = op(ser, pytd)

            assert_series_equal(lhs, rhs) 
Example 11
Project: edgedb   Author: edgedb   File: utils.py    License: Apache License 2.0 6 votes vote down vote up
def minimize_class_set_by_most_generic(
    schema: s_schema.Schema,
    classes: Iterable[so.InheritingObjectT]
) -> List[so.InheritingObjectT]:
    """Minimize the given set of objects by filtering out all subclasses."""

    classes = list(classes)
    mros = [set(p.get_ancestors(schema).objects(schema)) for p in classes]
    count = len(classes)
    smap = itertools.starmap

    # Return only those entries that do not have other entries in their mro
    result = [
        scls for i, scls in enumerate(classes)
        if not any(smap(set.__contains__,
                        ((mros[i], classes[j])
                         for j in range(count) if j != i)))
    ]

    return result 
Example 12
Project: edgedb   Author: edgedb   File: utils.py    License: Apache License 2.0 6 votes vote down vote up
def minimize_class_set_by_least_generic(
    schema: s_schema.Schema,
    classes: Iterable[so.InheritingObjectT]
) -> List[so.InheritingObjectT]:
    """Minimize the given set of objects by filtering out all superclasses."""

    classes = list(classes)
    mros = [set(p.get_ancestors(schema).objects(schema)) | {p}
            for p in classes]
    count = len(classes)
    smap = itertools.starmap

    # Return only those entries that are not present in other entries' mro
    result = [
        scls for i, scls in enumerate(classes)
        if not any(smap(set.__contains__,
                        ((mros[j], classes[i])
                         for j in range(count) if j != i)))
    ]

    return result 
Example 13
Project: BinderFilter   Author: dxwu   File: collections.py    License: MIT License 6 votes vote down vote up
def elements(self):
        '''Iterator over elements repeating each as many times as its count.

        >>> c = Counter('ABCABC')
        >>> sorted(c.elements())
        ['A', 'A', 'B', 'B', 'C', 'C']

        # Knuth's example for prime factors of 1836:  2**2 * 3**3 * 17**1
        >>> prime_factors = Counter({2: 2, 3: 3, 17: 1})
        >>> product = 1
        >>> for factor in prime_factors.elements():     # loop over factors
        ...     product *= factor                       # and multiply them
        >>> product
        1836

        Note, if an element's count has been set to zero or is a negative
        number, elements() will ignore it.

        '''
        # Emulate Bag.do from Smalltalk and Multiset.begin from C++.
        return _chain.from_iterable(_starmap(_repeat, self.iteritems()))

    # Override dict methods where necessary 
Example 14
Project: oss-ftp   Author: aliyun   File: collections.py    License: MIT License 6 votes vote down vote up
def elements(self):
        '''Iterator over elements repeating each as many times as its count.

        >>> c = Counter('ABCABC')
        >>> sorted(c.elements())
        ['A', 'A', 'B', 'B', 'C', 'C']

        # Knuth's example for prime factors of 1836:  2**2 * 3**3 * 17**1
        >>> prime_factors = Counter({2: 2, 3: 3, 17: 1})
        >>> product = 1
        >>> for factor in prime_factors.elements():     # loop over factors
        ...     product *= factor                       # and multiply them
        >>> product
        1836

        Note, if an element's count has been set to zero or is a negative
        number, elements() will ignore it.

        '''
        # Emulate Bag.do from Smalltalk and Multiset.begin from C++.
        return _chain.from_iterable(_starmap(_repeat, self.iteritems()))

    # Override dict methods where necessary 
Example 15
Project: concepts   Author: xflr6   File: tools.py    License: MIT License 6 votes vote down vote up
def maximal(iterable, comparison=operator.lt, _groupkey=operator.itemgetter(0)):
    """Yield the unique maximal elements from ``iterable`` using ``comparison``.

    >>> list(maximal([1, 2, 3, 3]))
    [3]

    >>> list(maximal([1]))
    [1]
    """
    iterable = set(iterable)
    if len(iterable) < 2:
        return iter(iterable)

    return (item
            for item, pairs in groupby(permutations(iterable, 2), key=_groupkey)
            if not any(starmap(comparison, pairs))) 
Example 16
Project: ibis   Author: ibis-project   File: rules.py    License: Apache License 2.0 6 votes vote down vote up
def _promote_numeric_binop(exprs, op):
    bounds, dtypes = [], []
    for arg in exprs:
        dtypes.append(arg.type())
        if hasattr(arg.op(), 'value'):
            # arg.op() is a literal
            bounds.append([arg.op().value])
        else:
            bounds.append(arg.type().bounds)

    # In some cases, the bounding type might be int8, even though neither
    # of the types are that small. We want to ensure the containing type is
    # _at least_ as large as the smallest type in the expression.
    values = starmap(op, product(*bounds))
    dtypes += [dt.infer(value, allow_overflow=True) for value in values]

    return dt.highest_precedence(dtypes) 
Example 17
Project: VSE-C   Author: ExplorerFreda   File: cli.py    License: MIT License 5 votes vote down vote up
def format_meters(caption, meters_kv, kv_format, glue):
    log_str = [caption]
    log_str.extend(itertools.starmap(kv_format.format, sorted(meters_kv.items())))
    return glue.join(log_str) 
Example 18
Project: gnocchi   Author: gnocchixyz   File: utils.py    License: Apache License 2.0 5 votes vote down vote up
def sequencial_map(fn, list_of_args):
    return list(itertools.starmap(fn, list_of_args)) 
Example 19
Project: gnocchi   Author: gnocchixyz   File: test_utils.py    License: Apache License 2.0 5 votes vote down vote up
def test_parallel_map_one(self):
        utils.parallel_map.MAX_WORKERS = 1
        starmap = itertools.starmap
        with mock.patch("itertools.starmap") as sm:
            sm.side_effect = starmap
            self.assertEqual([1, 2, 3],
                             utils.parallel_map(lambda x: x,
                                                [[1], [2], [3]]))
            sm.assert_called() 
Example 20
Project: gnocchi   Author: gnocchixyz   File: test_utils.py    License: Apache License 2.0 5 votes vote down vote up
def test_parallel_map_four(self):
        utils.parallel_map.MAX_WORKERS = 4
        starmap = itertools.starmap
        with mock.patch("itertools.starmap") as sm:
            sm.side_effect = starmap
            self.assertEqual([1, 2, 3],
                             utils.parallel_map(lambda x: x,
                                                [[1], [2], [3]]))
            sm.assert_not_called() 
Example 21
Project: jawfish   Author: war-and-code   File: __init__.py    License: MIT License 5 votes vote down vote up
def elements(self):
        '''Iterator over elements repeating each as many times as its count.

        >>> c = Counter('ABCABC')
        >>> sorted(c.elements())
        ['A', 'A', 'B', 'B', 'C', 'C']

        # Knuth's example for prime factors of 1836:  2**2 * 3**3 * 17**1
        >>> prime_factors = Counter({2: 2, 3: 3, 17: 1})
        >>> product = 1
        >>> for factor in prime_factors.elements():     # loop over factors
        ...     product *= factor                       # and multiply them
        >>> product
        1836

        Note, if an element's count has been set to zero or is a negative
        number, elements() will ignore it.

        '''
        # Emulate Bag.do from Smalltalk and Multiset.begin from C++.
        return _chain.from_iterable(_starmap(_repeat, self.items()))

    # Override dict methods where necessary 
Example 22
Project: jawfish   Author: war-and-code   File: pool.py    License: MIT License 5 votes vote down vote up
def starmapstar(args):
    return list(itertools.starmap(args[0], args[1]))

#
# Code run by worker processes
# 
Example 23
Project: jawfish   Author: war-and-code   File: pool.py    License: MIT License 5 votes vote down vote up
def starmap(self, func, iterable, chunksize=None):
        '''
        Like `map()` method but the elements of the `iterable` are expected to
        be iterables as well and will be unpacked as arguments. Hence
        `func` and (a, b) becomes func(a, b).
        '''
        return self._map_async(func, iterable, starmapstar, chunksize).get() 
Example 24
Project: jawfish   Author: war-and-code   File: pool.py    License: MIT License 5 votes vote down vote up
def starmap_async(self, func, iterable, chunksize=None, callback=None,
            error_callback=None):
        '''
        Asynchronous version of `starmap()` method.
        '''
        return self._map_async(func, iterable, starmapstar, chunksize,
                               callback, error_callback) 
Example 25
Project: olympe   Author: Parrot-Developers   File: messages.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _argsmap_from_args(cls, *args, **kwds):
        args = OrderedDict((zip(map(lambda a: a, cls.args_name), args)))
        args_set = set(args.keys())
        kwds_set = set(kwds.keys())
        if not args_set.isdisjoint(kwds_set):
            raise RuntimeError(
                "Message `{}` got multiple values for argument(s) {}".format(
                    cls.fullName, list(args_set & kwds_set)))
        args.update(kwds)

        # filter out None value
        args = OrderedDict([(k, v) for k, v in args.items() if v is not None])

        # enum conversion
        args = OrderedDict(starmap(
            lambda name, value: (name, cls.args_enum[name][value])
            if (name in cls.args_enum and isinstance(value, (bytes, str))) else (name, value),
            args.items()
        ))

        # bitfield conversion
        args = OrderedDict(starmap(
            lambda name, value: (name, cls.args_bitfield[name](value))
            if name in cls.args_bitfield else (name, value),
            args.items()
        ))

        args = OrderedDict(starmap(lambda k, v: (k, v), args.items()))
        return args 
Example 26
Project: olympe   Author: Parrot-Developers   File: messages.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _decode_args(cls, message_buffer):
        """
        Decode a ctypes message buffer into a list of python typed arguments. This also perform the
        necessary enum, bitfield and unicode conversions.
        """
        decoded_args = list(map(lambda ctype: ctypes.pointer(ctype()), cls.decode_ctypes_args))
        decoded_args_type = list(map(lambda ctype: ctypes.POINTER(ctype), cls.decode_ctypes_args))
        od.arsdk_cmd_dec.argtypes = od.arsdk_cmd_dec.argtypes[:2] + decoded_args_type

        res = od.arsdk_cmd_dec(message_buffer, cls.arsdk_desc, *decoded_args)

        # ctypes -> python type conversion
        decoded_args = list(map(
            lambda a: a.contents.value, decoded_args
        ))

        # bytes utf-8 -> str conversion
        decoded_args = list(map(
            lambda a: str(a, 'utf-8')
            if isinstance(a, bytes) else a,
            decoded_args
        ))

        # enum conversion
        decoded_args = list(starmap(
            lambda name, value: cls.args_enum[name](value)
            if name in cls.args_enum and value in cls.args_enum[name]._value2member_map_
            else value,
            zip(cls.args_name, decoded_args)
        ))

        # bitfield conversion
        decoded_args = list(map(
            lambda t: cls.args_bitfield[t[0]](t[1])
            if t[0] in cls.args_bitfield else t[1],
            zip(cls.args_name, decoded_args)
        ))

        return (res, decoded_args) 
Example 27
Project: recruit   Author: Frank-qlu   File: test_datetime64.py    License: Apache License 2.0 5 votes vote down vote up
def test_timedelta64_equal_timedelta_supported_ops(self, op):
        ser = Series([Timestamp('20130301'),
                      Timestamp('20130228 23:00:00'),
                      Timestamp('20130228 22:00:00'),
                      Timestamp('20130228 21:00:00')])

        intervals = ['D', 'h', 'm', 's', 'us']

        # TODO: unused
        # npy16_mappings = {'D': 24 * 60 * 60 * 1000000,
        #                   'h': 60 * 60 * 1000000,
        #                   'm': 60 * 1000000,
        #                   's': 1000000,
        #                   'us': 1}

        def timedelta64(*args):
            return sum(starmap(np.timedelta64, zip(args, intervals)))

        for d, h, m, s, us in product(*([range(2)] * 5)):
            nptd = timedelta64(d, h, m, s, us)
            pytd = timedelta(days=d, hours=h, minutes=m, seconds=s,
                             microseconds=us)
            lhs = op(ser, nptd)
            rhs = op(ser, pytd)

            tm.assert_series_equal(lhs, rhs) 
Example 28
Project: segpy   Author: sixty-north   File: strategies.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def spaced_ranges(min_num_ranges, max_num_ranges, min_interval, max_interval):
    """A Hypothesis strategy to produce separated, non-overlapping ranges.

    Args:
        min_num_ranges: The minimum number of ranges to produce. TODO: Correct?
        max_num_ranges: The maximum number of ranges to produce.
        min_interval: The minimum interval used for the lengths of the alternating ranges and spaces.
        max_interval: The maximum interval used for the lengths of the alternating ranges and spaces.
    """
    return integers(min_num_ranges, max_num_ranges)               \
           .map(lambda n: 2*n)                                                       \
           .flatmap(lambda n: lists(integers(min_interval, max_interval), min_size=n, max_size=n))  \
           .map(list).map(lambda lst: list(accumulate(lst)))                         \
           .map(lambda lst: list(batched(lst, 2)))                                   \
           .map(lambda pairs: list(starmap(range, pairs))) 
Example 29
Project: turkish-morphology   Author: google-research   File: reader.py    License: Apache License 2.0 5 votes vote down vote up
def read_lexicon_entries(path: str) -> Dict[int, _LexiconEntry]:
  """Reads lexicon entries of the TSV structured lexicon file from the path.

  Args:
    path: path to a file which contains TSV dump of lexicon entries.

  Raises:
    IOError: lexicon entries cannot be read from the 'path'.

  Returns:
    Lexicon file content as a dictionary. Keys are indices of the rows of the
    source TSV, values are the lexicon entries as dictionaries that contain
    field-value pairs for the columns of each row. Content for empty rows are
    pruned and lexicon entries are sorted by increasing row index. Returns an
    empty dictionary, if the TSV dump does not contain any lexicon entries.
  """
  with open(path, "r", encoding="utf-8") as reader:
    lines = reader.readlines()

  # Line 1 is assumed to be the TSV header. Any line below the header is
  # assumed to be a lexicon entry.
  header, entries = lines[0], lines[1:]

  if not entries:
    return collections.OrderedDict()

  field_names = _split(header)

  def _index_and_entry(index: int, line: str) -> Tuple[int, _LexiconEntry]:
    return index + 2, dict(zip(field_names, _split(line)))

  non_empty = ((i, l) for i, l in enumerate(entries) if not _empty(l))
  return collections.OrderedDict(itertools.starmap(_index_and_entry, non_empty)) 
Example 30
Project: turkish-morphology   Author: google-research   File: reader.py    License: Apache License 2.0 5 votes vote down vote up
def read_rule_definitions(path: str) -> Dict[int, _RuleDefinition]:
  """Reads morphotactics FST rule definitions from the path.

  Args:
    path: path to a text file which contains the definition of rewrite rules of
        morphotactics FST.

  Raises:
    IOError: morphotactics FST rule definitions cannot be read from the 'path'.

  Returns:
    Morphotactics FST rule definitions as a dictionary. Keys are indices of the
    lines of the source file, values are the list of whitespace tokenized tokens
    of each line. Content for lines those that are empty, only include comments,
    or only composed of whitespace characters are pruned and rule definitions
    are sorted by increasing line index. Returns an empty dictionary, if
    the text file does not contain any rule definitions.
  """
  with open(path, "r", encoding="utf-8") as reader:
    lines = reader.readlines()

  def _index_and_entry(index: int, line: str) -> Tuple[int, _RuleDefinition]:
    return index + 1, _whitespace_trimmed(line).split()

  rules = ((i, l) for i, l in enumerate(lines) if _rule(l))
  return collections.OrderedDict(itertools.starmap(_index_and_entry, rules))