本文整理汇总了Python中six.moves.zip_longest函数的典型用法代码示例。如果您正苦于以下问题:Python zip_longest函数的具体用法?Python zip_longest怎么用?Python zip_longest使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了zip_longest函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: __init__
def __init__(self, language_info, settings=None):
dictionary = {}
self._settings = settings
self.info = language_info
if 'skip' in language_info:
skip = map(methodcaller('lower'), language_info['skip'])
dictionary.update(zip_longest(skip, [], fillvalue=None))
if 'pertain' in language_info:
pertain = map(methodcaller('lower'), language_info['pertain'])
dictionary.update(zip_longest(pertain, [], fillvalue=None))
for word in ['monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday',
'january', 'february', 'march', 'april', 'may', 'june', 'july',
'august', 'september', 'october', 'november', 'december',
'year', 'month', 'week', 'day', 'hour', 'minute', 'second',
'ago']:
translations = map(methodcaller('lower'), language_info[word])
dictionary.update(zip_longest(translations, [], fillvalue=word))
dictionary.update(zip_longest(ALWAYS_KEEP_TOKENS, ALWAYS_KEEP_TOKENS))
dictionary.update(zip_longest(map(methodcaller('lower'),
DATEUTIL_PARSERINFO_KNOWN_TOKENS),
DATEUTIL_PARSERINFO_KNOWN_TOKENS))
self._dictionary = dictionary
self._no_word_spacing = language_info.get('no_word_spacing', False)
示例2: _load_data
def _load_data(self, languages=None, locales=None, region=None,
use_given_order=False, allow_conflicting_locales=False):
locale_dict = OrderedDict()
if locales:
invalid_locales = []
for locale in locales:
lang_reg = LOCALE_SPLIT_PATTERN.split(locale)
if len(lang_reg) == 1:
lang_reg.append('')
locale_dict[locale] = tuple(lang_reg)
if not _isvalidlocale(locale):
invalid_locales.append(locale)
if invalid_locales:
raise ValueError("Unknown locale(s): %s"
% ', '.join(map(repr, invalid_locales)))
if not allow_conflicting_locales:
if len(set(locales)) > len(set([t[0] for t in locale_dict.values()])):
raise ValueError("Locales should not have same language and different region")
else:
if languages is None:
languages = language_order
unsupported_languages = set(languages) - set(language_order)
if unsupported_languages:
raise ValueError("Unknown language(s): %s"
% ', '.join(map(repr, unsupported_languages)))
if region is None:
region = ''
locales = _construct_locales(languages, region)
locale_dict.update(zip_longest(locales,
tuple(zip_longest(languages, [], fillvalue=region))))
if not use_given_order:
locale_dict = OrderedDict(sorted(locale_dict.items(),
key=lambda x: language_order.index(x[1][0])))
for shortname, lang_reg in locale_dict.items():
if shortname not in self._loaded_locales:
lang, reg = lang_reg
if lang in self._loaded_languages:
locale = Locale(shortname, language_info=deepcopy(self._loaded_languages[lang]))
self._loaded_locales[shortname] = locale
else:
language_info = getattr(
import_module('dateparser.data.date_translation_data.' + lang), 'info')
language_info = convert_to_unicode(language_info)
locale = Locale(shortname, language_info=deepcopy(language_info))
self._loaded_languages[lang] = language_info
self._loaded_locales[shortname] = locale
yield shortname, self._loaded_locales[shortname]
示例3: _add
def _add(s, A, B):
# A + B
if len(A) == 1 and len(A[0]) == 1:
A = A[0][0]
return s.element_class(s, [[A + B[0][0]] + list(B[0][1:])] + list(B[1:]))
elif len(B) == 1 and len(B[0]) == 1:
B = B[0][0]
return s.element_class(s, [[A[0][0] + B] + list(A[0][1:])] + list(A[1:]))
ret = []
for x, y in zip_longest(A, B, fillvalue=[0]):
t = []
for xs, ys in zip_longest(x, y, fillvalue=0):
t += [xs + ys]
ret += [t]
return s.element_class(s, ret)
示例4: reconstruct_coincidences
def reconstruct_coincidences(self, coincidences, station_numbers=None,
offsets=None, progress=True, initials=None):
"""Reconstruct all coincidences
:param coincidences: a list of coincidence events, each consisting
of three or more (station_number, event) tuples.
:param station_numbers: list of station numbers, to only use
events from those stations.
:param offsets: dictionary with detector offsets for each station.
These detector offsets should be relative to one
detector from a specific station.
:param progress: if True show a progress bar while reconstructing.
:param initials: list of dictionaries with already reconstructed shower
parameters.
:return: list of theta, phi, and station numbers.
"""
if offsets is None:
offsets = {}
if initials is None:
initials = []
coincidences = pbar(coincidences, show=progress)
coin_init = zip_longest(coincidences, initials)
angles = [self.reconstruct_coincidence(coincidence, station_numbers,
offsets, initial)
for coincidence, initial in coin_init]
if len(angles):
theta, phi, nums = zip(*angles)
else:
theta, phi, nums = ((), (), ())
return theta, phi, nums
示例5: test_logging
def test_logging(self):
try:
foo()
except:
logging.critical("Got exception", exc_info=True)
expected = (
r'^WARNING$',
r'^warning here$',
r'^CRITICAL$',
r'^Got exception$',
r'^Traceback \(most recent call last\):$',
r'^ File ".+test_logging\.py", line [0-9]+, in test_logging$',
r'^ foo\(\)$',
r'^ File ".+test_logging\.py", line [0-9]+, in foo$',
r'^ \(in_foo=True\)$',
r'^ \(out_of_bar=True\)$',
r'^ baz\(\)$',
r'^ File ".+test_logging\.py", line [0-9]+, in baz$',
r'^ \(in_baz=True\)$',
r'^ raise ValueError\("ohno"\)$',
r'^ValueError: ohno$')
actual = self.output.getvalue().split('\n')
if actual and not actual[-1]:
actual = actual[:-1]
for a, e in zip_longest(actual, expected):
self.assertIsNotNone(re.search(e, a), "%r != %r" % (a, e))
示例6: test_parse_stream
def test_parse_stream(
self, structure_and_messages1, structure_and_messages2, structure_and_messages3
):
"""
L{Parser.parse_stream} returns an iterable of completed and then
incompleted tasks.
"""
_, messages1 = structure_and_messages1
_, messages2 = structure_and_messages2
_, messages3 = structure_and_messages3
# Need at least one non-dropped message in partial tree:
assume(len(messages3) > 1)
# Need unique UUIDs per task:
assume(
len(set(m[0][TASK_UUID_FIELD] for m in (messages1, messages2, messages3)))
== 3
)
# Two complete tasks, one incomplete task:
all_messages = (messages1, messages2, messages3[:-1])
all_tasks = list(
Parser.parse_stream(
[m for m in chain(*zip_longest(*all_messages)) if m is not None]
)
)
assertCountEqual(
self, all_tasks, [parse_to_task(msgs) for msgs in all_messages]
)
示例7: combine_slices
def combine_slices(slice1, slice2):
"""Return two tuples of slices combined sequentially.
These two should be equal:
x[ combine_slices(s1, s2) ] == x[s1][s2]
"""
out = []
for exp1, exp2 in zip_longest(
slice1, slice2, fillvalue=slice(None)):
if isinstance(exp1, int):
exp1 = slice(exp1, exp1+1)
if isinstance(exp2, int):
exp2 = slice(exp2, exp2+1)
start = (exp1.start or 0) + (exp2.start or 0)
step = (exp1.step or 1) * (exp2.step or 1)
if exp1.stop is None and exp2.stop is None:
stop = None
elif exp1.stop is None:
stop = (exp1.start or 0) + exp2.stop
elif exp2.stop is None:
stop = exp1.stop
else:
stop = min(exp1.stop, (exp1.start or 0) + exp2.stop)
out.append(slice(start, stop, step))
return tuple(out)
示例8: _apply_funcs
def _apply_funcs(return_vals, funcs):
"""
将func函数作用在被装饰的函数的返回值上
"""
# 检查iterable
if not isinstance(return_vals, tuple):
return_vals = (return_vals,)
try:
iter(funcs)
except TypeError:
funcs = (funcs,) if funcs else ()
# 检查函数
if not funcs:
return return_vals
# 函数和返回值不对齐
if 1 < len(return_vals) < len(funcs):
raise TypeError(
"In _apply_funcs(), len(funcs) == {} more than len(return_vals) == {}".format(
len(funcs), len(return_vals)
)
)
# 函数多于返回值
if 1 == len(return_vals) < len(funcs):
raise TypeError(
"In _apply_funcs(), only 1 return value with len(processors) == {}".format(len(funcs),
len(return_vals))
)
# 将函数作用在返回值上
return tuple([f(v) if f else v for v, f in zip_longest(return_vals, funcs)])
示例9: __init__
def __init__(self, rules=None, flags=0, branch_size=MAXGROUPS - 1):
"""Initialize index structures.
:param rules: list of tuples (regular expression, data)
:param flags: additional flags passed to SRE parser
:param branch_size: number of groups in a branch (max. 99)
"""
self._patterns = []
self.flags = flags
self.rules = rules or []
self.branch_size = min(branch_size, len(self.rules))
def make_pattern(rules, flags=0):
"""Compile a rules to single branch with groups."""
return re.compile('|'.join('(?P<I{name}>{regex})'.format(
name=name, regex=regex
) for regex, (name, creator) in rules), flags=flags)
for rules in zip_longest(*[iter(self.rules)] * self.branch_size):
self._patterns.append(make_pattern([
rule for rule in rules if rule is not None
]))
self._lookup = {
name: (name, creator) for _, (name, creator) in self.rules
}
示例10: histogram
def histogram(bidx, infile, bins, sampling, rgb):
"""
Histogram of raster values.
"""
with rio.open(infile) as src:
if bidx is not None:
indexes = [bidx]
else:
indexes = src.indexes
if rgb and len(indexes) < 3:
raise click.ClickException("Not enough bands to display a RGB histogram.")
elif rgb and len(indexes) >= 3:
colors = ('red', 'green', 'blue', 'violet')
else:
colors = ()
for b, color in zip_longest(indexes, colors, fillvalue=None):
data = np.zeros(
(src.height // sampling, src.width // sampling),
dtype=src.dtypes[src.indexes.index(b)])
data = src.read(indexes=b, out=data, masked=False)
plt.hist(data.flatten(), bins=bins, alpha=0.5, color=color)
plt.show()
示例11: cmp_like_py2
def cmp_like_py2(dict1, dict2): # type: (Dict[Text, Any], Dict[Text, Any]) -> int
"""
Comparision function to be used in sorting as python3 doesn't allow sorting
of different types like str() and int().
This function re-creates sorting nature in py2 of heterogeneous list of
`int` and `str`
"""
# extract lists from both dicts
first, second = dict1["position"], dict2["position"]
# iterate through both list till max of their size
for i, j in zip_longest(first, second):
if i == j:
continue
# in case 1st list is smaller
# should come first in sorting
if i is None:
return -1
# if 1st list is longer,
# it should come later in sort
elif j is None:
return 1
# if either of the list contains str element
# at any index, both should be str before comparing
if isinstance(i, str) or isinstance(j, str):
return 1 if str(i) > str(j) else -1
# int comparison otherwise
return 1 if i > j else -1
# if both lists are equal
return 0
示例12: _ComparePrereleaseStrings
def _ComparePrereleaseStrings(cls, s1, s2):
"""Compares the two given prerelease strings.
Args:
s1: str, The first prerelease string.
s2: str, The second prerelease string.
Returns:
1 if s1 is greater than s2, -1 if s2 is greater than s1, and 0 if equal.
"""
s1 = s1.split('.') if s1 else []
s2 = s2.split('.') if s2 else []
for (this, other) in zip_longest(s1, s2):
# They can't both be None because empty parts of the string split will
# come through as the empty string. None indicates it ran out of parts.
if this is None:
return 1
elif other is None:
return -1
# Both parts have a value
if this == other:
# This part is the same, move on to the next.
continue
if this.isdigit() and other.isdigit():
# Numerical comparison if they are both numbers.
return SemVer._CmpHelper(int(this), int(other))
# Lexical comparison if either is a string. Numbers will always sort
# before strings.
return SemVer._CmpHelper(this.lower(), other.lower())
return 0
示例13: assertContainsSameWords
def assertContainsSameWords(self, string1, string2):
try:
for w1, w2 in zip_longest(string1.split(), string2.split(), fillvalue=''):
self.assertEqual(w1, w2)
except AssertionError:
raise AssertionError("%r does not contain the same words as %r" % (string1,
string2))
示例14: create_sounding_dataset
def create_sounding_dataset(parent_group, dataset_name, in_data, shape_names=(), units=None):
"Creates a new dataset but with the data reshaped so that the first dim is the sounding one"
new_data = numpy.array(in_data)
try:
new_ds = parent_group.create_dataset(dataset_name, data=new_data.reshape(1, *new_data.shape))
except RuntimeError as e:
raise RuntimeError("Could not create dataset: %s with data: %s\n%s" % (dataset_name, new_data, e))
# Adds optionally passed shape names as an attribute to the dataset
# Missing dimensions will be called Dim%d
if type(shape_names) is StringType:
shape_names = [shape_names]
all_shape_names = []
for idx, s_name in zip_longest(list(range(len(new_ds.shape))), ["Retrieval"] + list(shape_names)):
if s_name:
all_shape_names.append(s_name)
else:
all_shape_names.append("Dim%d" % (idx+1))
new_ds.attrs["Shape"] = [ numpy.array("_".join(all_shape_names) + "_Array") ]
if units:
new_ds.attrs["Units"] = [ numpy.array(units) ]
return new_ds
示例15: make_date_range_tuples
def make_date_range_tuples(start, end, gap):
"""Make an iterable of date tuples for use in iterating forms
For example, a form might allow start and end dates and you want to iterate
it one week at a time starting on Jan 1 and ending on Feb 3:
>>> make_date_range_tuples(date(2017, 1, 1), date(2017, 2, 3), 7)
[(Jan 1, Jan 7), (Jan 8, Jan 14), (Jan 15, Jan 21), (Jan 22, Jan 28),
(Jan 29, Feb 3)]
:param start: date when the query should start.
:param end: date when the query should end.
:param gap: the number of days, inclusive, that a query should span at a
time.
:rtype list(tuple)
:returns: list of start, end tuples
"""
# We create a list of start dates and a list of end dates, then zip them
# together. If end_dates is shorter than start_dates, fill the last value
# with the original end date.
start_dates = [d.date() for d in rrule(DAILY, interval=gap, dtstart=start,
until=end)]
end_start = start + datetime.timedelta(days=gap - 1)
end_dates = [d.date() for d in rrule(DAILY, interval=gap, dtstart=end_start,
until=end)]
return list(zip_longest(start_dates, end_dates, fillvalue=end))