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


Python itertools.cycle方法代码示例

本文整理汇总了Python中itertools.cycle方法的典型用法代码示例。如果您正苦于以下问题:Python itertools.cycle方法的具体用法?Python itertools.cycle怎么用?Python itertools.cycle使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在itertools的用法示例。


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

示例1: run

# 需要导入模块: import itertools [as 别名]
# 或者: from itertools import cycle [as 别名]
def run(self):
        self.message_info("Running")

        colors = cycle([Color.red, Color.purple, Color.yellow, Color.blue, Color.white])

        snd = DuploSpeaker.sounds
        sounds = cycle([snd.brake, snd.station, snd.water, snd.horn, snd.steam])

        self.message_info('Please move the train to start the program')
        while not self.go:
            await self.led.set_color(next(colors))
            await sleep(0.3)

        for i in range(5):
            await self.led.set_color(next(colors))       # Cycle through the colors
            #await self.speaker.play_sound(next(sounds))  # cycle through the sounds
            tgt_speed = 20 + i*15                        # Keep increasing the speed
            await self.motor.ramp_speed(tgt_speed, 2000)
            self.message_info(f"Set speed to {i}")
            await sleep(3)

        self.message_info("Done") 
开发者ID:virantha,项目名称:bricknil,代码行数:24,代码来源:duplo_train.py

示例2: showWelcomeAnimation

# 需要导入模块: import itertools [as 别名]
# 或者: from itertools import cycle [as 别名]
def showWelcomeAnimation():
    """Shows welcome screen animation of flappy bird"""
    # index of player to blit on screen
    playerIndexGen = cycle([0, 1, 2, 1])

    playery = int((SCREENHEIGHT - PLAYER[IM_HEIGTH]) / 2)

    basex = 0

    # player shm for up-down motion on welcome screen
    playerShmVals = {"val": 0, "dir": 1}

    return {
        "playery": playery + playerShmVals["val"],
        "basex": basex,
        "playerIndexGen": playerIndexGen,
    } 
开发者ID:chncyhn,项目名称:flappybird-qlearning-bot,代码行数:19,代码来源:learn.py

示例3: run

# 需要导入模块: import itertools [as 别名]
# 或者: from itertools import cycle [as 别名]
def run(self):
        self.message_info("Running")
        self.motor_speed = 0
        self.keep_running = True
        self.sensor_change = False
        self.go = False

        # Blink the color  from purple and yellow
        colors = cycle([Color.purple, Color.yellow])
        while not self.go:  # Wait until the hub button is pushed
            await self.train_led.set_color(next(colors))
            await sleep(1)

        colors = cycle([Color.green, Color.orange])
        # Ready to go, let's change the color to green!
        while self.keep_running:
            if self.sensor_change:
                await self.train_led.set_color(next(colors))
                await self.motor.ramp_speed(self.motor_speed, 900)  # Ramp to new speed in 0.9 seconds
                self.sensor_change = False
                await sleep(1)
                await self.train_led.set_color(next(colors))
            else:
                await sleep(1) 
开发者ID:virantha,项目名称:bricknil,代码行数:26,代码来源:train_all.py

示例4: __setitem__

# 需要导入模块: import itertools [as 别名]
# 或者: from itertools import cycle [as 别名]
def __setitem__(self, key, value):
        if isinstance(key, numbers.Integral):
            self.data[key] = value
        else:
            if not isinstance(value, (type(self),
                                      compat.Sequence)):
                # broadcast value
                value = itertools.cycle([value])

            if isinstance(key, np.ndarray) and key.dtype == 'bool':
                # masking
                for i, (k, v) in enumerate(zip(key, value)):
                    if k:
                        assert isinstance(v, self.dtype.type)
                        self.data[i] = v
            else:
                for k, v in zip(key, value):
                    assert isinstance(v, self.dtype.type)
                    self.data[k] = v 
开发者ID:Frank-qlu,项目名称:recruit,代码行数:21,代码来源:array.py

示例5: count

# 需要导入模块: import itertools [as 别名]
# 或者: from itertools import cycle [as 别名]
def count(self, lines):
        # use the name server's prefix lookup to get all registered wordcounters
        with locate_ns() as ns:
            all_counters = ns.list(prefix="example.dc2.wordcount.")

        # chop the text into chunks that can be distributed across the workers
        # uses futures so that it runs the counts in parallel
        # counter is selected in a round-robin fashion from list of all available counters
        with futures.ThreadPoolExecutor() as pool:
            roundrobin_counters = cycle(all_counters.values())
            tasks = []
            for chunk in grouper(200, lines):
                tasks.append(pool.submit(self.count_chunk, next(roundrobin_counters), chunk))

            # gather the results
            print("Collecting %d results (counted in parallel)..." % len(tasks))
            totals = Counter()
            for task in futures.as_completed(tasks):
                try:
                    totals.update(task.result())
                except Pyro5.errors.CommunicationError as x:
                    raise Pyro5.errors.PyroError("Something went wrong in the server when collecting the responses: "+str(x))
            return totals 
开发者ID:irmen,项目名称:Pyro5,代码行数:25,代码来源:servers.py

示例6: read_fastq

# 需要导入模块: import itertools [as 别名]
# 或者: from itertools import cycle [as 别名]
def read_fastq(filename):
    """
    return a stream of FASTQ entries, handling gzipped and empty files
    """
    if not filename:
        return itertools.cycle((None,))
    if filename == "-":
        filename_fh = sys.stdin
    elif filename.endswith('gz'):
        if is_python3():
            filename_fh = gzip.open(filename, mode='rt')
        else:
            filename_fh = BufferedReader(gzip.open(filename, mode='rt'))
    else:
        filename_fh = open(filename)
    return stream_fastq(filename_fh) 
开发者ID:vals,项目名称:umis,代码行数:18,代码来源:umis.py

示例7: start

# 需要导入模块: import itertools [as 别名]
# 或者: from itertools import cycle [as 别名]
def start(self, e):
        for index in cycle(range(len(self.MESSAGE))):
            if e.is_set():
                break
            if not self.MESSAGE[index].isalpha():
                continue
            for c in self.CYCLES:
                buff = list(self.MESSAGE)
                buff.append(c)

                try:
                    if sys.stdout.encoding.upper() == 'UTF-8':
                        buff[index] = self.TABLE[buff[index]]
                    else:
                        buff[index] = buff[index].swapcase()
                except KeyError:
                    pass

                sys.stdout.write(''.join(buff))
                time.sleep(0.05)
                sys.stdout.write('\r')
                sys.stdout.flush() 
开发者ID:daniloaleixo,项目名称:bovespaStockRatings,代码行数:24,代码来源:waitingbar.py

示例8: test_IOBase_finalize

# 需要导入模块: import itertools [as 别名]
# 或者: from itertools import cycle [as 别名]
def test_IOBase_finalize(self):
        # Issue #12149: segmentation fault on _PyIOBase_finalize when both a
        # class which inherits IOBase and an object of this class are caught
        # in a reference cycle and close() is already in the method cache.
        class MyIO(self.IOBase):
            def close(self):
                pass

        # create an instance to populate the method cache
        MyIO()
        obj = MyIO()
        obj.obj = obj
        wr = weakref.ref(obj)
        del MyIO
        del obj
        support.gc_collect()
        self.assertIsNone(wr(), wr) 
开发者ID:IronLanguages,项目名称:ironpython2,代码行数:19,代码来源:test_io.py

示例9: _test_close_open_io

# 需要导入模块: import itertools [as 别名]
# 或者: from itertools import cycle [as 别名]
def _test_close_open_io(self, io_func, nb_workers=5):
        def worker():
            self._create_file()
            funcs = itertools.cycle((
                lambda: io_func(),
                lambda: self._close_and_reopen_file(),
            ))
            for f in funcs:
                if not self.do_continue:
                    break
                try:
                    f()
                except (IOError, ValueError):
                    pass
        self._run_workers(worker, nb_workers)
        if test_support.verbose:
            # Useful verbose statistics when tuning this test to take
            # less time to run but still ensuring that its still useful.
            #
            # the percent of close calls that raised an error
            percent = 100. - 100.*self.close_success_count/self.close_count
            print self.close_count, ('%.4f ' % percent), 
开发者ID:IronLanguages,项目名称:ironpython2,代码行数:24,代码来源:test_file2k.py

示例10: __init__

# 需要导入模块: import itertools [as 别名]
# 或者: from itertools import cycle [as 别名]
def __init__(self, urls):
        """
        >>> client = Client(['http://host-1:4001', 'http://host-2:4001'])
        :param urls: List of addresses of IDA containers including the published port
        """
        if isinstance(urls, str):
            urls = [urls]
        if urls is None or not any(urls):
            raise ValueError('Invalide "urls" value')
        self._urls = itertools.cycle(urls) 
开发者ID:Cisco-Talos,项目名称:BASS,代码行数:12,代码来源:bindiff.py

示例11: __init__

# 需要导入模块: import itertools [as 别名]
# 或者: from itertools import cycle [as 别名]
def __init__(self, proxies: list):
        self._proxies = proxies
        self._proxies_cycle = cycle(proxies) 
开发者ID:mlouielu,项目名称:twstock,代码行数:5,代码来源:proxy.py

示例12: proxies

# 需要导入模块: import itertools [as 别名]
# 或者: from itertools import cycle [as 别名]
def proxies(self, proxies: list):
        if not isinstance(proxies, list):
            raise ValueError('Proxies only accept list')

        self._proxies = proxies
        self._proxies_cycle = cycle(proxies) 
开发者ID:mlouielu,项目名称:twstock,代码行数:8,代码来源:proxy.py

示例13: __init__

# 需要导入模块: import itertools [as 别名]
# 或者: from itertools import cycle [as 别名]
def __init__(self,
                 font_size=10,
                 char='䦗',
                 background='#000000',
                 title='img2html by xlzd',
                 font_family='monospace',
                 progress_callback=None):
        self.font_size = font_size
        self.background = background
        self.title = title
        self.font_family = font_family
        if isinstance(char, str):
            char = char.decode('utf-8')
        self.char = cycle(char)
        self._prg_cb = progress_callback or _progress_callback 
开发者ID:xlzd,项目名称:img2html,代码行数:17,代码来源:converter.py

示例14: plot_clusters

# 需要导入模块: import itertools [as 别名]
# 或者: from itertools import cycle [as 别名]
def plot_clusters(coords, clusters, s=1, colors=None):
    if coords.shape[0] != clusters.shape[0]:
        sys.stderr.write(
            'Error: mismatch, {} cells, {} labels\n'
            .format(coords.shape[0], clusters.shape[0])
        )
        exit(1)

    if colors is None:
        colors = np.array(
            list(islice(cycle([
                '#377eb8', '#ff7f00', '#4daf4a',
                '#f781bf', '#a65628', '#984ea3',
                '#999999', '#e41a1c', '#dede00',
                '#ffe119', '#e6194b', '#ffbea3',
                '#911eb4', '#46f0f0', '#f032e6',
                '#d2f53c', '#008080', '#e6beff',
                '#aa6e28', '#800000', '#aaffc3',
                '#808000', '#ffd8b1', '#000080',
                '#808080', '#fabebe', '#a3f4ff'
            ]), int(max(clusters) + 1)))
        )

    plt.figure()
    plt.scatter(coords[:, 0], coords[:, 1],
                c=colors[clusters], s=s)

# Put datasets into a single matrix with the intersection of all genes. 
开发者ID:brianhie,项目名称:scanorama,代码行数:30,代码来源:scanorama.py

示例15: run_until_complete

# 需要导入模块: import itertools [as 别名]
# 或者: from itertools import cycle [as 别名]
def run_until_complete(self, *coroutines):
        """
        Executes a set of coroutines that communicate between each other. Each
        one is, in order, passed the output of the previous coroutine until
        one is exhausted. If a coroutine does not initially yield data (that
        is, its first action is to receive data), the calling code should prime
        it by using the 'server' decorator on this class.

        Once a coroutine is exhausted, the method performs a final check to
        ensure that all other coroutines are exhausted. This ensures that all
        assertions in those coroutines got executed.
        """
        looping_coroutines = itertools.cycle(coroutines)
        data = None

        for coro in looping_coroutines:
            try:
                data = coro.send(data)
            except StopIteration:
                break

        for coro in coroutines:
            try:
                next(coro)
            except StopIteration:
                continue
            else:
                pytest.fail("Coroutine %s not exhausted" % coro) 
开发者ID:python-hyper,项目名称:hyper-h2,代码行数:30,代码来源:coroutine_tests.py


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