本文整理汇总了Python中itertools.count方法的典型用法代码示例。如果您正苦于以下问题:Python itertools.count方法的具体用法?Python itertools.count怎么用?Python itertools.count使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类itertools
的用法示例。
在下文中一共展示了itertools.count方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: format_mask
# 需要导入模块: import itertools [as 别名]
# 或者: from itertools import count [as 别名]
def format_mask(x):
"""
Formats a mask into a readable string.
Args:
x (ndarray): an array with the mask;
Returns:
A readable string with the mask.
"""
x = numpy.asanyarray(x)
if len(x) == 0:
return "(empty)"
if x.dtype == bool:
x = numpy.argwhere(x)[:, 0]
grps = tuple(list(g) for _, g in groupby(x, lambda n, c=count(): n-next(c)))
return ",".join("{:d}-{:d}".format(i[0], i[-1]) if len(i) > 1 else "{:d}".format(i[0]) for i in grps)
示例2: _jpeg_content_length
# 需要导入模块: import itertools [as 别名]
# 或者: from itertools import count [as 别名]
def _jpeg_content_length(p):
"""
Determines the length of the content of the JPEG file stored at `p` in bytes, i.e., size of the file without the
header. Note: Note sure if this works for all JPEGs...
:param p: path to a JPEG file
:return: length of content
"""
with open(p, 'rb') as f:
last_byte = ''
header_end_i = None
for i in itertools.count():
current_byte = f.read(1)
if current_byte == b'':
break
# some files somehow contain multiple FF DA sequences, don't know what that means
if header_end_i is None and last_byte == b'\xff' and current_byte == b'\xda':
header_end_i = i
last_byte = current_byte
# at this point, i is equal to the size of the file
return i - header_end_i - 2 # minus 2 because all JPEG files end in FF D0
示例3: __init__
# 需要导入模块: import itertools [as 别名]
# 或者: from itertools import count [as 别名]
def __init__(self, pywren_config, storage_backend):
self.pywren_config = pywren_config
self.backend = storage_backend
self._created_cobjects_n = itertools.count()
try:
module_location = 'pywren_ibm_cloud.storage.backends.{}'.format(self.backend)
sb_module = importlib.import_module(module_location)
storage_config = self.pywren_config[self.backend]
storage_config['user_agent'] = 'pywren-ibm-cloud/{}'.format(__version__)
StorageBackend = getattr(sb_module, 'StorageBackend')
self.storage_handler = StorageBackend(storage_config)
except Exception as e:
raise NotImplementedError("An exception was produced trying to create the "
"'{}' storage backend: {}".format(self.backend, e))
示例4: __init__
# 需要导入模块: import itertools [as 别名]
# 或者: from itertools import count [as 别名]
def __init__(*args, **kwds):
'''Create a new, empty Counter object. And if given, count elements
from an input iterable. Or, initialize the count from another mapping
of elements to their counts.
>>> c = Counter() # a new, empty counter
>>> c = Counter('gallahad') # a new counter from an iterable
>>> c = Counter({'a': 4, 'b': 2}) # a new counter from a mapping
>>> c = Counter(a=4, b=2) # a new counter from keyword args
'''
if not args:
raise TypeError("descriptor '__init__' of 'Counter' object "
"needs an argument")
self = args[0]
args = args[1:]
if len(args) > 1:
raise TypeError('expected at most 1 arguments, got %d' % len(args))
super(Counter, self).__init__()
self.update(*args, **kwds)
示例5: elements
# 需要导入模块: import itertools [as 别名]
# 或者: from itertools import count [as 别名]
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
示例6: __add__
# 需要导入模块: import itertools [as 别名]
# 或者: from itertools import count [as 别名]
def __add__(self, other):
'''Add counts from two counters.
>>> Counter('abbb') + Counter('bcc')
Counter({'b': 4, 'c': 2, 'a': 1})
'''
if not isinstance(other, Counter):
return NotImplemented
result = Counter()
for elem, count in self.items():
newcount = count + other[elem]
if newcount > 0:
result[elem] = newcount
for elem, count in other.items():
if elem not in self and count > 0:
result[elem] = count
return result
示例7: __sub__
# 需要导入模块: import itertools [as 别名]
# 或者: from itertools import count [as 别名]
def __sub__(self, other):
''' Subtract count, but keep only results with positive counts.
>>> Counter('abbbc') - Counter('bccd')
Counter({'b': 2, 'a': 1})
'''
if not isinstance(other, Counter):
return NotImplemented
result = Counter()
for elem, count in self.items():
newcount = count - other[elem]
if newcount > 0:
result[elem] = newcount
for elem, count in other.items():
if elem not in self and count < 0:
result[elem] = 0 - count
return result
示例8: __or__
# 需要导入模块: import itertools [as 别名]
# 或者: from itertools import count [as 别名]
def __or__(self, other):
'''Union is the maximum of value in either of the input counters.
>>> Counter('abbb') | Counter('bcc')
Counter({'b': 3, 'c': 2, 'a': 1})
'''
if not isinstance(other, Counter):
return NotImplemented
result = Counter()
for elem, count in self.items():
other_count = other[elem]
newcount = other_count if count < other_count else count
if newcount > 0:
result[elem] = newcount
for elem, count in other.items():
if elem not in self and count > 0:
result[elem] = count
return result
示例9: __and__
# 需要导入模块: import itertools [as 别名]
# 或者: from itertools import count [as 别名]
def __and__(self, other):
''' Intersection is the minimum of corresponding counts.
>>> Counter('abbb') & Counter('bcc')
Counter({'b': 1})
'''
if not isinstance(other, Counter):
return NotImplemented
result = Counter()
for elem, count in self.items():
other_count = other[elem]
newcount = count if count < other_count else other_count
if newcount > 0:
result[elem] = newcount
return result
示例10: count
# 需要导入模块: import itertools [as 别名]
# 或者: from itertools import count [as 别名]
def count(start=0, step=1):
"""
``itertools.count`` in Py 2.6 doesn't accept a step
parameter. This is an enhanced version of ``itertools.count``
for Py2.6 equivalent to ``itertools.count`` in Python 2.7+.
"""
while True:
yield start
start += step
########################################################################
### ChainMap (helper for configparser and string.Template)
### From the Py3.4 source code. See also:
### https://github.com/kkxue/Py2ChainMap/blob/master/py2chainmap.py
########################################################################
示例11: parse_columns
# 需要导入模块: import itertools [as 别名]
# 或者: from itertools import count [as 别名]
def parse_columns(text, base, count):
# Parse the columns from the table definition. Columns start with
# a short record length indicator, followed by type and sequence
# information (each a short), and the name (prefixed by the length).
columns = []
for i in range(count):
if len(text[base:]) < 8:
break
col_len, = struct.unpack_from('H', text, base)
base = base + 2
if len(text[base:]) < col_len:
break
col_data = text[base - 1:base - 1 + col_len]
type_, col_id = struct.unpack_from('>HH', col_data, 0)
text_len, = struct.unpack_from('>I', col_data, 4)
col_name = decode_text(col_data[8:8 + text_len])
if col_name is None:
continue
columns.append({
'id': col_id,
'name': col_name,
'type': type_
})
base = base + col_len
return columns
示例12: _flatten_index
# 需要导入模块: import itertools [as 别名]
# 或者: from itertools import count [as 别名]
def _flatten_index(data):
"""Flatten the index as a combination of the former index and the columns."""
data = copy.deepcopy(data)
data_flat = []
counter = itertools.count()
for series_or_df in data:
series_or_df.index = series_or_df.index.map(str)
# Unstack pandas.DataFrames and pandas.Series to add
# columns/name to index.
if isinstance(series_or_df, pd.DataFrame):
df = series_or_df.rename(columns=str)
# pandas.Series without a name are named using a counter to avoid duplicate
# indexes.
elif isinstance(series_or_df, pd.Series) and series_or_df.name is None:
df = series_or_df.to_frame(name=str(next(counter)))
else:
df = series_or_df.to_frame(str(series_or_df.name))
# Columns to the index.
df = df.unstack()
df.index = df.index.to_flat_index().str.join("_")
data_flat.append(df)
return pd.concat(data_flat)
示例13: read
# 需要导入模块: import itertools [as 别名]
# 或者: from itertools import count [as 别名]
def read(self, count=None):
if self.closed:
raise ValueError('read of closed file.')
if count is None or count < 0:
count = max(self.size - self.tell(), 0)
data = b''
while count > 0:
# Go to current offset, possibly opening new file.
self.seek(0, 1)
extra = self.fh.read(count)
if not extra:
break
count -= len(extra)
if not data: # avoid copies for first read.
data = extra
else:
data += extra
return data
示例14: test_threadlocal_garbage
# 需要导入模块: import itertools [as 别名]
# 或者: from itertools import count [as 别名]
def test_threadlocal_garbage(self):
if platform.system() == 'Darwin':
self.skip('queue issues; see #1474')
success = itertools.count()
def getpage():
host = '%s:%s' % (self.interface(), self.PORT)
if self.scheme == 'https':
c = HTTPSConnection(host)
else:
c = HTTPConnection(host)
try:
c.putrequest('GET', '/')
c.endheaders()
response = c.getresponse()
body = response.read()
self.assertEqual(response.status, 200)
self.assertEqual(body, b'Hello world!')
finally:
c.close()
next(success)
ITERATIONS = 25
ts = [
threading.Thread(target=getpage)
for _ in range(ITERATIONS)
]
for t in ts:
t.start()
for t in ts:
t.join()
self.assertEqual(next(success), ITERATIONS)
示例15: __init__
# 需要导入模块: import itertools [as 别名]
# 或者: from itertools import count [as 别名]
def __init__(self, initial_content: BatchOfKwargs = None):
self._register: t.Dict[int, Dto] = {}
self._id_generator = count(1)
if initial_content:
self.batch_insert(initial_content)