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


Python next函数代码示例

本文整理汇总了Python中next函数的典型用法代码示例。如果您正苦于以下问题:Python next函数的具体用法?Python next怎么用?Python next使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了next函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: __next__

 def __next__(self):
     """
     Return the next error node
     """
     for child in self.children:
         yield child
     next(self.parent)
开发者ID:sbuss,项目名称:pyx12,代码行数:7,代码来源:error_handler.py

示例2: iterunique

def iterunique(source, key):
    # assume source is sorted
    # first need to sort the data
    it = iter(source)

    hdr = next(it)
    yield tuple(hdr)

    # convert field selection into field indices
    if key is None:
        indices = range(len(hdr))
    else:
        indices = asindices(hdr, key)

    # now use field indices to construct a _getkey function
    # N.B., this may raise an exception on short rows, depending on
    # the field selection
    getkey = operator.itemgetter(*indices)

    prev = next(it)
    prev_key = getkey(prev)
    prev_comp_ne = True

    for curr in it:
        curr_key = getkey(curr)
        curr_comp_ne = curr_key != prev_key
        if prev_comp_ne and curr_comp_ne:
            yield tuple(prev)
        prev = curr
        prev_key = curr_key
        prev_comp_ne = curr_comp_ne

    # last one?
    if prev_comp_ne:
        yield prev
开发者ID:rogerkwoodley,项目名称:petl,代码行数:35,代码来源:dedup.py

示例3: _sparql_query_pattern_part

    def _sparql_query_pattern_part(
            self,
            bind=None,
            values=None,
            indent=' ',
    ):
        assert bind is None or isinstance(bind, dict)
        assert values is None or (
            isinstance(values, dict) and
            isinstance(next(six.iterkeys(values)), Iterable) and
            isinstance(next(six.itervalues(values)), Iterable)
        )

        res = ''
        if values:
            res = indent + self._sparql_values_part(values, indent) + '\n'
        res += indent + self._sparql_triples_part(indent) + '\n'
        if bind:
            res += '%sFILTER(\n%s\n%s)\n' % (
                indent,
                ' &&\n'.join([
                    '%s %s=%s' % (indent, k.n3(), self.curify(v))
                    for k, v in sorted(bind.items())
                    if k in self.vars_in_graph
                ]),
                indent,
            )
        return res
开发者ID:RDFLib,项目名称:graph-pattern-learner,代码行数:28,代码来源:graph_pattern.py

示例4: read_tss_anno

def read_tss_anno(anno, gene_filter):
	positions = {}
	g_filter = []
	c = 0
	if gene_filter:
		with open(gene_filter) as f:
			for line in f:
				line = line.rstrip()
				word = line.split("\t")
				g_filter.append(word[0])
	with open(anno) as f:
		next(f)
		for line in f:
			line = line.rstrip()
			word = line.split("\t")
			if word[1] == "MT": chrom = "chrM"
			elif word[1] == "X": chrom = "chrX"
			elif word[1] == "Y": chrom = "chrY"
			elif word[1].isdigit(): chrom = "chr" + word[1]
			if word[4] == "1": 
				strand = "+"
			else: 
				strand = "-"
			if g_filter:
				if word[0] in g_filter:
					positions[word[0]] = (chrom, int(word[2]), strand)
					c +=  1
			else:
				positions[word[0]] = (chrom, int(word[2]), strand)
				c +=  1
	return positions
开发者ID:pdl30,项目名称:pyribotools,代码行数:31,代码来源:plotter.py

示例5: window

def window(iter, pre_size=1, post_size=1):
	"""
	Given an iterable, return a new iterable which yields triples of
	(pre, item, post), where pre and post are the items preceeding and
	following the item (or None if no such item is appropriate). pre
	and post will always be pre_size and post_size in length.

	>>> example = window(range(10), pre_size=2)
	>>> pre, item, post = next(example)
	>>> pre
	(None, None)
	>>> post
	(1,)
	>>> next(example)
	((None, 0), 1, (2,))
	>>> list(example)[-1]
	((7, 8), 9, (None,))
	"""
	pre_iter, iter = itertools.tee(iter)
	pre_iter = itertools.chain((None,) * pre_size, pre_iter)
	pre_iter = nwise(pre_iter, pre_size)
	post_iter, iter = itertools.tee(iter)
	post_iter = itertools.chain(post_iter, (None,) * post_size)
	post_iter = nwise(post_iter, post_size)
	next(post_iter, None)
	return six.moves.zip(pre_iter, iter, post_iter)
开发者ID:FrobtheBuilder,项目名称:vIRC,代码行数:26,代码来源:itertools.py

示例6: test_pqueue_by_servicebus_client_iter_messages_simple

def test_pqueue_by_servicebus_client_iter_messages_simple(live_servicebus_config, partitioned_queue):
    client = ServiceBusClient(
        service_namespace=live_servicebus_config['hostname'],
        shared_access_key_name=live_servicebus_config['key_name'],
        shared_access_key_value=live_servicebus_config['access_key'],
        debug=True)

    queue_client = client.get_queue(partitioned_queue)
    with queue_client.get_receiver(idle_timeout=5, mode=ReceiveSettleMode.PeekLock) as receiver:

        with queue_client.get_sender() as sender:
            for i in range(10):
                message = Message("Iter message no. {}".format(i))
                sender.send(message)

        count = 0
        for message in receiver:
            print_message(message)
            message.complete()
            with pytest.raises(MessageAlreadySettled):
                message.complete()
            with pytest.raises(MessageAlreadySettled):
                message.renew_lock()
            count += 1

        with pytest.raises(InvalidHandlerState):
            next(receiver)
    assert count == 10
开发者ID:Azure,项目名称:azure-sdk-for-python,代码行数:28,代码来源:test_partitioned_queues.py

示例7: test_post_process_extensions_generator_response

    def test_post_process_extensions_generator_response(self):
        class Controller(object):
            def index(self, req, pants=None):
                return pants

        controller = Controller()
        resource = wsgi.Resource(controller)

        called = []

        def extension1(req):
            yield
            called.append(1)

        def extension2(req):
            yield
            called.append(2)
            yield 'foo'

        ext1 = extension1(None)
        next(ext1)
        ext2 = extension2(None)
        next(ext2)

        response = resource.post_process_extensions([ext2, ext1],
                                                    None, None, {})

        self.assertEqual(called, [2])
        self.assertEqual(response, 'foo')
开发者ID:Milstein,项目名称:nova,代码行数:29,代码来源:test_wsgi.py

示例8: select_map

    def select_map(self, latitude, longitude):
        """
        Find and display a nearby track by latitude / longitude
        The selection will favor a previously selected track in the nearby area
        :param latitude
        :type  latitude float
        :param longitude
        :type longitude float
        :returns the selected track, or None if there are no nearby tracks
        :type Track 
        """

        if not latitude or not longitude:
            return None

        point = GeoPoint.fromPoint(latitude, longitude)
        nearby_tracks = self.track_manager.find_nearby_tracks(point)

        saved_tracks = self.get_pref_track_selections()

        saved_nearby_tracks = [t for t in nearby_tracks if t.track_id in saved_tracks]

        # select the saved nearby track or just a nearby track
        track = next(iter(saved_nearby_tracks), None)
        track = next(iter(nearby_tracks), None) if track is None else track

        if self.track != track:
            # only update the trackmap if it's changing
            self._select_track(track)
        return track
开发者ID:autosportlabs,项目名称:RaceCapture_App,代码行数:30,代码来源:analysismap.py

示例9: readFile

	def readFile(self):
		file = "/Users/molgenis/Documents/graduation_project/mendelianViolationFiles/mendelian_violation_allDiploid_Xadjusted.txt"
		
		mother_DP = []
		father_DP = []
		child_DP = []
		transmissionProbability = []

		with open(file) as f:
			next(f)
			for line in f:
				if line != "":
					columns = line.split('\t')
					
					mother_DP.append(columns[6])
					father_DP.append(columns[10])
					child_DP.append(columns[14])
					transmissionProbability.append(columns[4])
				else:
					next(line)
					
		self.countThresholdMother(mother_DP)
		self.countThresholdFather(father_DP)
		self.countThresholdChild(child_DP)
		self.countTP(transmissionProbability)
开发者ID:joerivandervelde,项目名称:graduation-project,代码行数:25,代码来源:parseMendelianViolations.py

示例10: unmunch_all

 def unmunch_all(self):
     self.parse_aff()
     with codecs.open(self.dic_path, "r", "utf-8") as fp:
         next(fp)  # Skip first line.
         for line in fp:
             line = line.split(u" ")[0]
             self.apply_suffix(u"", line)
开发者ID:daliboris,项目名称:hunspell,代码行数:7,代码来源:hunspell.py

示例11: getContents

    def getContents(self, group):
        if not self._checkFsEndpointPath():
            return

        logger.debug("Scanning for posts (shallow) in: %s" %
                     self.fs_endpoint_path)
        year_pattern = ShallowPostsSource.YEAR_PATTERN
        file_pattern = ShallowPostsSource.FILE_PATTERN
        _, year_dirs, __ = next(osutil.walk(self.fs_endpoint_path))
        year_dirs = [d for d in year_dirs if year_pattern.match(d)]
        for yd in year_dirs:
            if year_pattern.match(yd) is None:
                logger.warning(
                    "'%s' is not formatted as 'YYYY' and will be ignored. "
                    "Is that a typo?")
                continue
            year = int(yd)
            year_dir = os.path.join(self.fs_endpoint_path, yd)

            _, __, filenames = next(osutil.walk(year_dir))
            for f in filenames:
                match = file_pattern.match(f)
                if match is None:
                    name, ext = os.path.splitext(f)
                    logger.warning(
                        "'%s' is not formatted as 'MM-DD_slug-title.%s' "
                        "and will be ignored. Is that a typo?" % (f, ext))
                    continue
                yield self._makeContentItem(
                    os.path.join(yd, f),
                    match.group(3),
                    year,
                    int(match.group(1)),
                    int(match.group(2)))
开发者ID:ludovicchabant,项目名称:PieCrust2,代码行数:34,代码来源:posts.py

示例12: get_apreture_dic

def get_apreture_dic():
    ffline = ff.FortranRecordReader('(3X,a16,3I4,F17.4,F17.10,2F12.3,I4,2x,a16)')
    dic = {}
    with open(MIX_FILE) as f:
        for _ in range(31):
            next(f)
        # for i in range(LAST_RING_ELEMENT):
        while True:
            try:
                line = f.readline()
                if not line:
                    break
                hh = ffline.read(line)
                device_type = int(hh[2])
                if device_type == 2:
                    # this is a drift space, ignore it
                    continue
                    # name = 'DRIFT'
                else:
                    name = hh[0].strip()
                aperture = hh[6]
                if name not in dic:
                    dic.update({name: aperture})
                    # print('{},\t{},\t,{}\n'.format(name, device_type, aperture))
                    # if aperture == 0:
                    #    print(name)
            except:
                pass
    return dic
开发者ID:xaratustrah,项目名称:pymirko,代码行数:29,代码来源:pymirko.py

示例13: load_transactions_mock

 def load_transactions_mock(input_file, **kwargs):
     """ Mock for apyori.load_transactions. """
     eq_(kwargs['delimiter'], delimiter)
     eq_(next(input_file), inputs[0])
     yield iter(input_transactions[0])
     eq_(next(input_file), inputs[1])
     yield iter(input_transactions[1])
开发者ID:pombredanne,项目名称:apyori,代码行数:7,代码来源:test_main.py

示例14: async_step_import

    async def async_step_import(self, user_input):
        """Import a config entry."""
        if self.hass.config_entries.async_entries(DOMAIN):
            return self.async_abort(reason='already_setup')

        self._scan_interval = user_input[KEY_SCAN_INTERVAL]
        if user_input[CONF_HOST] != DOMAIN:
            self._hosts.append(user_input[CONF_HOST])

        if not await self.hass.async_add_executor_job(
                os.path.isfile, self.hass.config.path(TELLDUS_CONFIG_FILE)):
            return await self.async_step_user()

        conf = await self.hass.async_add_executor_job(
            load_json, self.hass.config.path(TELLDUS_CONFIG_FILE))
        host = next(iter(conf))

        if user_input[CONF_HOST] != host:
            return await self.async_step_user()

        host = CLOUD_NAME if host == 'tellduslive' else host
        return self.async_create_entry(
            title=host,
            data={
                CONF_HOST: host,
                KEY_SCAN_INTERVAL: self._scan_interval.seconds,
                KEY_SESSION: next(iter(conf.values())),
            })
开发者ID:fbradyirl,项目名称:home-assistant,代码行数:28,代码来源:config_flow.py

示例15: sepLine2List

def sepLine2List(file2sep, sep="-"):
    """

    :param file:
    default:combine
    """
    try:
        fhIn = open(file2sep,'r')
        all = set()
        for line in fhIn:
            if line == '':
                next()
            line = line.replace(sep,'\n').rstrip()
            line = line.split('\n')
            for i in line:
                all.add(i)
        fhIn.close()

        fhOut = open(file2sep+'_sep','w')
        for i in all:
            fhOut.write(i+'\n')
        fhOut.close()
        print("Entry number left: %s" % len(all))
    except:
        print "error in sepLine2List"
        return False
开发者ID:18dubu,项目名称:ChunhuaLab_2016BBW,代码行数:26,代码来源:data.py


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