本文整理汇总了Python中itertools.zip_longest方法的典型用法代码示例。如果您正苦于以下问题:Python itertools.zip_longest方法的具体用法?Python itertools.zip_longest怎么用?Python itertools.zip_longest使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类itertools
的用法示例。
在下文中一共展示了itertools.zip_longest方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: result_match
# 需要导入模块: import itertools [as 别名]
# 或者: from itertools import zip_longest [as 别名]
def result_match(result, value, path=None):
path = [] if path is None else path
if result is _missing:
return False, path, result, value
if isinstance(value, dict):
for k, v in value.items():
ok, sp, sr, sv = result_match(result[k], v, path + [k])
if not ok:
return ok, sp, sr, sv
elif isinstance(value, (list, tuple)):
pairs = zip_longest(result, value, fillvalue=_missing)
for i, (v1, v2) in enumerate(pairs):
ok, sp, sr, sv = result_match(v1, v2, path + [i])
if not ok:
return ok, sp, sr, sv
elif result != value:
return False, path, result, value
return True, None, None, None
示例2: tabulate
# 需要导入模块: import itertools [as 别名]
# 或者: from itertools import zip_longest [as 别名]
def tabulate(vals):
# From pfmoore on GitHub:
# https://github.com/pypa/pip/issues/3651#issuecomment-216932564
assert len(vals) > 0
sizes = [0] * max(len(x) for x in vals)
for row in vals:
sizes = [max(s, len(str(c))) for s, c in zip_longest(sizes, row)]
result = []
for row in vals:
display = " ".join([str(c).ljust(s) if c is not None else ''
for s, c in zip_longest(sizes, row)])
result.append(display)
return result, sizes
示例3: loose_version_compare
# 需要导入模块: import itertools [as 别名]
# 或者: from itertools import zip_longest [as 别名]
def loose_version_compare(a, b):
for i, j in zip_longest(a.version, b.version, fillvalue=''):
if type(i) != type(j):
i = str(i)
j = str(j)
if i == j:
continue
elif i < j:
return -1
else: # i > j
return 1
#Longer version strings with equal prefixes are equal, but if one version string is longer than it is greater
aLen = len(a.version)
bLen = len(b.version)
if aLen == bLen:
return 0
elif aLen < bLen:
return -1
else:
return 1
示例4: base_equal
# 需要导入模块: import itertools [as 别名]
# 或者: from itertools import zip_longest [as 别名]
def base_equal(self, ob1, ob2):
if type(ob1) != type(ob2):
return False
def cmp(obj1, obj2):
if isinstance(obj1, np.ndarray):
return np.array_equal(obj1, obj2)
elif isinstance(obj1, Iterable) and \
not isinstance(obj1, str) and \
isinstance(obj2, Iterable) and \
not isinstance(obj2, str):
return all(cmp(it1, it2) for it1, it2 in itertools.zip_longest(obj1, obj2))
elif hasattr(obj1, 'key') and hasattr(obj2, 'key'):
return obj1.key == obj2.key
elif isinstance(obj1, ReferenceType) and isinstance(obj2, ReferenceType):
return cmp(obj1(), obj2())
else:
return obj1 == obj2
for slot in ob1.__slots__:
if not cmp(getattr(ob1, slot, None), getattr(ob2, slot, None)):
return False
return True
示例5: compare_tokens
# 需要导入模块: import itertools [as 别名]
# 或者: from itertools import zip_longest [as 别名]
def compare_tokens(content, expected_types, expected_values=None,
expected_lineno=None, expected_lexpos=None):
lexer = AtfLexer().lexer
lexer.input(content)
if expected_values is None:
expected_values = repeat(None)
if expected_lineno is None:
expected_lineno = repeat(None)
if expected_lexpos is None:
expected_lexpos = repeat(None)
for e_type, e_value, e_lineno, e_lexpos, token in zip_longest(
expected_types,
expected_values,
expected_lineno,
expected_lexpos,
lexer):
if token is None and e_type is None:
break
assert token.type == e_type
if e_value:
assert token.value == e_value
if e_lineno:
assert token.lineno == e_lineno
if e_lexpos:
assert token.lexpos == e_lexpos
示例6: _format_args
# 需要导入模块: import itertools [as 别名]
# 或者: from itertools import zip_longest [as 别名]
def _format_args(args, defaults=None, annotations=None):
values = []
if args is None:
return ""
if annotations is None:
annotations = []
if defaults is not None:
default_offset = len(args) - len(defaults)
packed = itertools.zip_longest(args, annotations)
for i, (arg, annotation) in enumerate(packed):
if isinstance(arg, Tuple):
values.append("(%s)" % _format_args(arg.elts))
else:
argname = arg.name
if annotation is not None:
argname += ":" + annotation.as_string()
values.append(argname)
if defaults is not None and i >= default_offset:
if defaults[i - default_offset] is not None:
values[-1] += "=" + defaults[i - default_offset].as_string()
return ", ".join(values)
示例7: __add__
# 需要导入模块: import itertools [as 别名]
# 或者: from itertools import zip_longest [as 别名]
def __add__(self, other):
if isinstance(other, type(self)):
other_tiers = other._tiers
elif isinstance(other, collections.abc.Iterable):
other_tiers = other
new_tiers = []
for tier1,x in itertools.zip_longest(self._tiers, other_tiers):
if tier1 is None:
tier1 = []
if isinstance(x, str) and len(x) > 1:
new_tier = tier1 + [x]
elif isinstance(x, collections.abc.Iterable):
new_tier = tier1 + list(x)
elif x is not None:
return NotImplemented
else:
new_tier = tier1
new_tiers.append(new_tier)
return type(self)(new_tiers, callback=self._callback)
示例8: check_maker
# 需要导入模块: import itertools [as 别名]
# 或者: from itertools import zip_longest [as 别名]
def check_maker(maker: tp.Callable[[], tp.Iterator[experiments.Experiment]]) -> None:
generators = [maker() for _ in range(2)]
# check 1 sample
sample = next(maker())
assert isinstance(sample, experiments.Experiment)
# check names, coherence and non-randomness
for k, (elem1, elem2) in enumerate(itertools.zip_longest(*generators)):
assert not elem1.is_incoherent, f"Incoherent settings should be filtered out from generator:\n{elem1}"
try:
assert elem1 == elem2 # much faster but lacks explicit message
except AssertionError:
testing.printed_assert_equal(
elem1.get_description(),
elem2.get_description(),
err_msg=f"Two paths on the generator differed (see element #{k})\n"
"Generators need to be deterministic in order to split the workload!",
)
示例9: __init__
# 需要导入模块: import itertools [as 别名]
# 或者: from itertools import zip_longest [as 别名]
def __init__(self, iterable, num_shards, shard_id, fill_value=None):
if shard_id < 0 or shard_id >= num_shards:
raise ValueError('shard_id must be between 0 and num_shards')
sharded_len = int(math.ceil(len(iterable) / float(num_shards)))
itr = map(
operator.itemgetter(1),
itertools.zip_longest(
range(sharded_len),
itertools.islice(iterable, shard_id, len(iterable), num_shards),
fillvalue=fill_value,
),
)
super().__init__(
itr,
start=int(math.ceil(getattr(iterable, 'n', 0) / float(num_shards))),
total=sharded_len,
)
示例10: veval_ast_arguments
# 需要导入模块: import itertools [as 别名]
# 或者: from itertools import zip_longest [as 别名]
def veval_ast_arguments(astc : 'AstContext', local_field : 'values.Field', graph : 'Graph', context : 'functions.VEvalContext' = None):
assert(isinstance(astc.nast, gast.gast.arguments))
lineprop = utils.LineProperty(astc.lineno, astc.filename)
ret = functions.FunctionArgCollection()
argspec = inspect.FullArgSpec(astc.nast.args, astc.nast.vararg, astc.nast.kwarg,
astc.nast.defaults, astc.nast.kwonlyargs, astc.nast.kw_defaults, None)
assert not argspec.kwonlyargs, "Keyword only args are not supported"
assert not argspec.varargs, "Varaibale arguments *args is not supported"
assert not argspec.varkw, "Variable keywords **kwargs is not supported"
defaults = [veval_ast(astc.c(default), local_field, graph, context) for default in argspec.defaults]
arg_list = []
for k, v in itertools.zip_longest(reversed(argspec.args), defaults):
arg_list.append((k.id, v))
# reverse the list
for k, v in reversed(arg_list):
ret.add_arg(k, v)
return ret
示例11: safeZip
# 需要导入模块: import itertools [as 别名]
# 或者: from itertools import zip_longest [as 别名]
def safeZip(listOfLists, enforceLength):
"""
A safe version of python's zip()
If two sublists are of different sizes, python's zip will truncate
the output to be the smaller of the two.
safeZip throws an exception if the size of the any sublist is different
from the rest.
"""
if enforceLength is True:
length = len(listOfLists[0])
assert(all([length == len(subList) for subList in listOfLists]))
try:
zipFunc = itertools.izip_longest # Python 2.x
except AttributeError:
zipFunc = itertools.zip_longest # Python 3.x
return zipFunc(*listOfLists)
示例12: shared_parent
# 需要导入模块: import itertools [as 别名]
# 或者: from itertools import zip_longest [as 别名]
def shared_parent(self):
"""
Returns the folder object that is the shared parent (the root of
a shared folder hierarchy) or None if there is no shared parent.
"""
root = self
a, b = itertools.tee(reversed(self.breadcrumbs()))
next(b, None)
for folder, parent in itertools.zip_longest(a, b):
if folder.shared:
root = folder
if parent is None or not parent.shared:
break
return root
示例13: append
# 需要导入模块: import itertools [as 别名]
# 或者: from itertools import zip_longest [as 别名]
def append(self, *row):
self.rows.append(row)
self.maxs = [max(max_cur, len(row_entry))
for max_cur, row_entry in
itertools.zip_longest(self.maxs, row, fillvalue=0)]
示例14: runner
# 需要导入模块: import itertools [as 别名]
# 或者: from itertools import zip_longest [as 别名]
def runner(x, base, chunk):
for i, j in itertools.zip_longest(divmod_iter_chunking(x, base, chunk), divmod_iter_basic(x, base)):
if i is None:
print("phooey")
else:
assert i == j
示例15: _parse_data
# 需要导入模块: import itertools [as 别名]
# 或者: from itertools import zip_longest [as 别名]
def _parse_data(elem: etree.Element) -> Iterable[dict]:
"""
Parses a generic container element enclosing a single COLUMNS and multiple DATA elems, and
returns a generator of dicts with keys given by the COLUMNS elem and values given by each
DATA elem. The container elem may optionally contain a DELIMITER elem to define the delimiter
used, otherwise a default of '\t' is assumed.
<RETS ReplyCode="0" ReplyText="Success">
<DELIMITER value="09"/>
<COLUMNS> LIST_87 LIST_105 LIST_1 </COLUMNS>
<DATA> 2016-12-01T00:08:10 5489015 20160824051756837742000000 </DATA>
<DATA> 2016-12-01T00:10:02 5497756 20160915055426038684000000 </DATA>
<DATA> 2016-12-01T00:10:26 5528935 20161123230848928777000000 </DATA>
<DATA> 2016-12-01T00:10:52 5528955 20161123234916869427000000 </DATA>
<DATA> 2016-12-01T00:14:31 5530021 20161127221848669500000000 </DATA>
</RETS>
"""
delimiter = _parse_delimiter(elem)
columns_elem = _find_or_raise(elem, 'COLUMNS')
columns = _parse_data_line(columns_elem, delimiter)
data_elems = elem.findall('DATA')
return (OrderedDict(zip_longest(columns, _parse_data_line(data, delimiter)))
for data in data_elems)