當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。