本文整理匯總了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")
示例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,
}
示例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)
示例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
示例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
示例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)
示例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()
示例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)
示例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),
示例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)
示例11: __init__
# 需要導入模塊: import itertools [as 別名]
# 或者: from itertools import cycle [as 別名]
def __init__(self, proxies: list):
self._proxies = proxies
self._proxies_cycle = cycle(proxies)
示例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)
示例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
示例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.
示例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)