本文整理汇总了Python中itertools.izip_longest方法的典型用法代码示例。如果您正苦于以下问题:Python itertools.izip_longest方法的具体用法?Python itertools.izip_longest怎么用?Python itertools.izip_longest使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类itertools
的用法示例。
在下文中一共展示了itertools.izip_longest方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: result_match
# 需要导入模块: import itertools [as 别名]
# 或者: from itertools import izip_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 izip_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: compare_tokens
# 需要导入模块: import itertools [as 别名]
# 或者: from itertools import izip_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
示例4: assert_iterators_equal
# 需要导入模块: import itertools [as 别名]
# 或者: from itertools import izip_longest [as 别名]
def assert_iterators_equal(self, xs, ys, test_id, limit=None):
# check that an iterator xs matches the expected results ys,
# up to a given limit.
if limit is not None:
xs = itertools.islice(xs, limit)
ys = itertools.islice(ys, limit)
sentinel = object()
pairs = itertools.izip_longest(xs, ys, fillvalue=sentinel)
for i, (x, y) in enumerate(pairs):
if x == y:
continue
elif x == sentinel:
self.fail('{}: iterator ended unexpectedly '
'at position {}; expected {}'.format(test_id, i, y))
elif y == sentinel:
self.fail('{}: unexpected excess element {} at '
'position {}'.format(test_id, x, i))
else:
self.fail('{}: wrong element at position {};'
'expected {}, got {}'.format(test_id, i, y, x))
示例5: merge
# 需要导入模块: import itertools [as 别名]
# 或者: from itertools import izip_longest [as 别名]
def merge(self, n):
"""Merge new file into old
"""
if os.path.isfile(n[:-4]):
old = self.read_file(n[:-4]).splitlines()
if os.path.isfile(n):
new = self.read_file(n).splitlines()
with open(n[:-4], "w") as out:
for l1, l2 in itertools.izip_longest(old, new):
if l1 is None:
l1 = ""
if l2 is None:
l2 = ""
if l1 != l2:
out.write(l2 + "\n")
else:
out.write(l1 + "\n")
print("The file {0} merged in file {1}".format(
n.split("/")[-1], n[:-4].split("/")[-1]))
示例6: safeZip
# 需要导入模块: import itertools [as 别名]
# 或者: from itertools import izip_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)
示例7: run
# 需要导入模块: import itertools [as 别名]
# 或者: from itertools import izip_longest [as 别名]
def run(options, image, command=[], env={}, cpus=None, mems=None, ports=[]):
envs = env.items() if isinstance(env, dict) else env
pairs = [("-e", "%s=%s" % (k, v)) for k, v in envs]
if ports != []: # NB: Forces external call to pre-fetch image
port_pairings = list(itertools.izip_longest(ports, inner_ports(image)))
log.info("Port pairings (Mesos, Docker) // %r", port_pairings)
for allocated, target in port_pairings:
if allocated is None:
log.warning("Container exposes more ports than were allocated")
break
options += ["-p", "%d:%d" % (allocated, target or allocated)]
argv = ["run"] + options
argv += ["-c", str(cpus)] if cpus else []
argv += ["-m", str(mems)] if mems else []
argv += [_ for __ in pairs for _ in __] # This is just flatten
argv += [image] + command
return docker(*argv)
示例8: test_izip_longest
# 需要导入模块: import itertools [as 别名]
# 或者: from itertools import izip_longest [as 别名]
def test_izip_longest():
yield (verify_same, izip_longest, _zip_longest, None, [], [])
yield (verify_same, izip_longest, _zip_longest, None, [], [5, 4])
yield (verify_same, izip_longest, _zip_longest, None, [2], [5, 4])
yield (verify_same, izip_longest, _zip_longest, None, [7, 9], [5, 4])
yield (verify_same, izip_longest, _zip_longest, None, [7, 9],
[4], [2, 9, 3])
yield (verify_same, izip_longest, _zip_longest, None, [7, 9], [4], [])
yield (verify_same, izip_longest, _zip_longest, None, [7], [4], [],
[5, 9])
yield (verify_same, partial(izip_longest, fillvalue=-1),
partial(_zip_longest, fillvalue=-1), None,
[7], [4], [], [5, 9])
yield (verify_pickle, izip_longest, _zip_longest, 3, 2, [7, 9, 8], [1, 2])
yield (verify_pickle, izip_longest, _zip_longest, 3, 1, [7, 9, 8], [1, 2])
示例9: _add_argument_diff
# 需要导入模块: import itertools [as 别名]
# 或者: from itertools import izip_longest [as 别名]
def _add_argument_diff(actual, expected, indent=0, acc=None):
first = False
if not acc:
acc = []
first = True
if type(actual) != type(expected):
acc.append("{}{!r} {} {!r}".format(" " * indent * 2, actual, "==" if actual == expected else "!=", expected))
elif isinstance(actual, dict):
for k in set(actual.keys() + expected.keys()):
acc.append("{}{}:".format(" " * indent * 2, k))
a = actual.get(k)
e = expected.get(k)
if a != e:
_add_argument_diff(a, e, indent + 1, acc)
elif isinstance(actual, list):
for a, e in itertools.izip_longest(actual, expected):
acc.append("{}-".format(" " * indent * 2))
if a != e:
_add_argument_diff(a, e, indent + 1, acc)
else:
acc.append("{}{!r} {} {!r}".format(" " * indent * 2, actual, "==" if actual == expected else "!=", expected))
if first:
return "\n".join(acc)
示例10: print_goal
# 需要导入模块: import itertools [as 别名]
# 或者: from itertools import izip_longest [as 别名]
def print_goal(goal, achieved=False, level=None, indent=2):
""" Print a goals description with its icon. Achieved (True/False) will choose the correct icon
from the goal. If a level is specified, a tracker line will be added under the icon showing
the current level out of the required level for the goal. If level is > the required level,
achieved will be set to true.
"""
from clint.textui import puts
from clint.textui import indent as _indent
from clint.textui.cols import columns, console_width
if level is not None and level >= goal['level']:
achieved = True
icon = (goal['icon'].achieved() if achieved else goal['icon'].unachieved()).split('\n')
maxiw = max([len(str(_)) for _ in icon])
descw = console_width({})-maxiw-(indent + 4)
desc = '{0}\n{1}\n\n{2}'.format(goal['name'], '-'*len(goal['name']),
columns([goal['description'], descw])).split('\n')
if level is not None:
if level > goal['level']:
level = goal['level']
maxitw = max([len(_) for _ in icon])
icon.append(("%d/%d" % (level, goal['level'])).center(maxitw))
with _indent(indent):
for i, d in _zip_longest(icon, desc):
puts("{1:{0}} {2}".format(maxiw, str(i) if i is not None else "",
d.strip() if d is not None else ""))
示例11: assertIterEqual
# 需要导入模块: import itertools [as 别名]
# 或者: from itertools import izip_longest [as 别名]
def assertIterEqual(self, expected_iter, actual_iter):
for expected, actual in itertools.izip_longest(expected_iter, actual_iter):
self.assertIsNotNone(
expected,
msg='actual has unexpected elements starting with %s' % str(actual))
self.assertIsNotNone(
actual,
msg='actual is missing elements starting with %s' % str(expected))
self.assertEqual(actual.group('proc_id'), expected[0])
self.assertEqual(actual.group('thread_id'), expected[1])
self.assertEqual(actual.group('log_level'), expected[2])
self.assertEqual(actual.group('component'), expected[3])
self.assertEqual(actual.group('message'), expected[4])
with self.assertRaises(StopIteration):
next(actual_iter)
with self.assertRaises(StopIteration):
next(expected_iter)
示例12: value
# 需要导入模块: import itertools [as 别名]
# 或者: from itertools import izip_longest [as 别名]
def value(self, value):
value_parts = value.split('.')
# If we have too many children, cut the list down to size.
# pylint: disable=attribute-defined-outside-init
self._children = self._children[:len(value_parts)]
# Update child nodes.
for child, value_part in itertools.izip_longest(
self._children, value_parts):
if child:
# Modify existing children. This helps preserve comments and spaces.
child.children[-1].value = value_part
else:
# Add children as needed.
token_snippets = [
snippet.TokenSnippet.Create(token.DOT, '.'),
snippet.TokenSnippet.Create(token.NAME, value_part),
]
self._children.append(snippet.Symbol(symbol.trailer, token_snippets))
示例13: value
# 需要导入模块: import itertools [as 别名]
# 或者: from itertools import izip_longest [as 别名]
def value(self, value):
value_parts = value.split('.')
for value_part in value_parts:
if keyword.iskeyword(value_part):
raise ValueError('%s is a reserved keyword.' % value_part)
# If we have too many children, cut the list down to size.
# pylint: disable=attribute-defined-outside-init
self._children = self._children[:len(value_parts)*2-1]
# Update child nodes.
for child, value_part in itertools.izip_longest(
self._children[::2], value_parts):
if child:
# Modify existing children. This helps preserve comments and spaces.
child.value = value_part
else:
# Add children as needed.
self._children.append(snippet.TokenSnippet.Create(token.DOT, '.'))
self._children.append(
snippet.TokenSnippet.Create(token.NAME, value_part))
示例14: chunk
# 需要导入模块: import itertools [as 别名]
# 或者: from itertools import izip_longest [as 别名]
def chunk(self, iterable, n, fillvalue=None):
"itertools recipe: Collect data into fixed-length chunks or blocks"
args = [iter(iterable)] * n
return izip_longest(fillvalue=fillvalue, *args)
示例15: grouper
# 需要导入模块: import itertools [as 别名]
# 或者: from itertools import izip_longest [as 别名]
def grouper(iterable, n, fillvalue=None):
args = [iter(iterable)] * n
return (filter(None, values) for values
in izip_longest(fillvalue=fillvalue, *args))