本文整理匯總了Python中functools.cmp_to_key方法的典型用法代碼示例。如果您正苦於以下問題:Python functools.cmp_to_key方法的具體用法?Python functools.cmp_to_key怎麽用?Python functools.cmp_to_key使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類functools
的用法示例。
在下文中一共展示了functools.cmp_to_key方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: cmp_to_key
# 需要導入模塊: import functools [as 別名]
# 或者: from functools import cmp_to_key [as 別名]
def cmp_to_key(mycmp):
"""Convert a cmp= function into a key= function"""
class K(object):
__slots__ = ['obj']
def __init__(self, obj, *args):
self.obj = obj
def __lt__(self, other):
return mycmp(self.obj, other.obj) < 0
def __gt__(self, other):
return mycmp(self.obj, other.obj) > 0
def __eq__(self, other):
return mycmp(self.obj, other.obj) == 0
def __le__(self, other):
return mycmp(self.obj, other.obj) <= 0
def __ge__(self, other):
return mycmp(self.obj, other.obj) >= 0
def __ne__(self, other):
return mycmp(self.obj, other.obj) != 0
def __hash__(self):
raise TypeError('hash not implemented')
return K
# Back up our definitions above in case they're useful
示例2: tags
# 需要導入模塊: import functools [as 別名]
# 或者: from functools import cmp_to_key [as 別名]
def tags(self):
if self.git_repo is None or len(self.git_repo.tags) == 0:
raise exceptions.NoTagsException(self, "Cannot find tags")
# Build a list of valid version names only.
# Raise an exception only if the most recent
# version name is invalid.
versions = []
for tag in self.git_repo.tags:
try:
versions.append(self.parse_version(tag.name))
except exceptions.InvalidVersionException as e:
if tag == self.git_repo.tags[-1]:
raise e
return sorted(versions, key=cmp_to_key(SemverCmp))
示例3: mount_all
# 需要導入模塊: import functools [as 別名]
# 或者: from functools import cmp_to_key [as 別名]
def mount_all(self):
def compare(a, b):
if len(a[0]) > len(b[0]):
return 1
elif len(a[0]) == len(b[0]):
return 0
else:
return -1
roots = self.os_inspects()
if roots:
for root in roots:
mps = self.g.inspect_get_mountpoints(root)
mps.sort(key=cmp_to_key(compare))
for mp_dev in mps:
try:
msg = "Mount dev '%s' partitions '%s' to '%s'"
logging.info(msg % (root, mp_dev[1], mp_dev[0]))
self.g.mount(mp_dev[1], mp_dev[0])
except RuntimeError as err_msg:
logging.info("%s (ignored)" % err_msg)
else:
raise exceptions.TestError(
"inspect_vm: no operating systems found")
示例4: link_names
# 需要導入模塊: import functools [as 別名]
# 或者: from functools import cmp_to_key [as 別名]
def link_names(self):
'''OrderedSet of link names (L#).'''
try:
from pyats.tcl.internal import DictionaryCompare
topo_devices = list(self.devices.values())
topo_links = set()
for topo_dev in topo_devices:
topo_links |= set(topo_dev.links)
sLs = [topo_link.link_name for topo_link in topo_links]
sLs = OrderedSet(sorted(sLs, key=functools.cmp_to_key(DictionaryCompare)))
return sLs
except ImportError:
# Considering users with no sourced tcl environment
pass
except Exception:
return
示例5: soGetAllLengths
# 需要導入模塊: import functools [as 別名]
# 或者: from functools import cmp_to_key [as 別名]
def soGetAllLengths(diam, blind):
if blind:
lmin, lmax = (6, 25)
else:
b, c, h, d, lmin, lmax = SOPEMTable[diam]
list = []
for len in SOLengths:
l = float(len)
if l >= lmin and l <= lmax:
list.append(len)
try: # py3
import functools
sorted(list, key = functools.cmp_to_key(FastenerBase.NumCompare))
except:
list.sort(cmp = FastenerBase.NumCompare)
return list
# h = clMakePressNut('M5','1')
示例6: _sort_skeletons_by_dist_to_center
# 需要導入模塊: import functools [as 別名]
# 或者: from functools import cmp_to_key [as 別名]
def _sort_skeletons_by_dist_to_center(self, skeletons):
''' Skeletons are sorted based on the distance
between neck and image center, from small to large.
A skeleton near center will be processed first and be given a smaller human id.
Here the center is defined as (0.5, 0.5), although it's not accurate due to h_scale.
'''
def calc_dist(p1, p2): return (
(p1[0] - p2[0])**2 + (p1[1] - p2[1])**2)**0.5
def cost(skeleton):
x1, y1 = self._get_neck(skeleton)
return calc_dist((x1, y1), (0.5, 0.5)) # dist to center
def cmp(a, b): return (a > b)-(a < b)
def mycmp(sk1, sk2): return cmp(cost(sk1), cost(sk2))
sorted_skeletons = sorted(skeletons, key=functools.cmp_to_key(mycmp))
return sorted_skeletons
示例7: test_undetected_mutation
# 需要導入模塊: import functools [as 別名]
# 或者: from functools import cmp_to_key [as 別名]
def test_undetected_mutation(self):
# Python 2.4a1 did not always detect mutation
memorywaster = []
for i in range(20):
def mutating_cmp(x, y):
L.append(3)
L.pop()
return (x > y) - (x < y)
L = [1,2]
self.assertRaises(ValueError, L.sort, key=cmp_to_key(mutating_cmp))
def mutating_cmp(x, y):
L.append(3)
del L[:]
return (x > y) - (x < y)
self.assertRaises(ValueError, L.sort, key=cmp_to_key(mutating_cmp))
memorywaster = [memorywaster]
#==============================================================================
示例8: test_reverse_stability
# 需要導入模塊: import functools [as 別名]
# 或者: from functools import cmp_to_key [as 別名]
def test_reverse_stability(self):
data = [(random.randrange(100), i) for i in range(200)]
copy1 = data[:]
copy2 = data[:]
def my_cmp(x, y):
x0, y0 = x[0], y[0]
return (x0 > y0) - (x0 < y0)
def my_cmp_reversed(x, y):
x0, y0 = x[0], y[0]
return (y0 > x0) - (y0 < x0)
data.sort(key=cmp_to_key(my_cmp), reverse=True)
copy1.sort(key=cmp_to_key(my_cmp_reversed))
self.assertEqual(data, copy1)
copy2.sort(key=lambda x: x[0], reverse=True)
self.assertEqual(data, copy2)
#==============================================================================
示例9: _get_relevant_migrations
# 需要導入模塊: import functools [as 別名]
# 或者: from functools import cmp_to_key [as 別名]
def _get_relevant_migrations(migration_scripts, current_version, new_version):
relevant_migrations = []
for migration in migration_scripts:
migration_original_version, migration_new_version = _get_migration_versions(
migration)
if not migration_original_version or not migration_new_version:
continue
if Upgrader.compareVersions(new_version, current_version) >= 0:
if Upgrader.compareVersions(
migration_original_version, migration_new_version) > 0:
continue
if Upgrader.compareVersions(current_version, migration_original_version) <= 0 \
and Upgrader.compareVersions(new_version, migration_new_version) >= 0:
relevant_migrations.append(migration)
else:
if Upgrader.compareVersions(
migration_new_version, migration_original_version) > 0:
continue
if Upgrader.compareVersions(current_version, migration_original_version) >= 0 \
and Upgrader.compareVersions(new_version, migration_new_version) <= 0:
relevant_migrations.append(migration)
relevant_migrations = sorted(
relevant_migrations, key=cmp_to_key(_compare_migration_scripts))
return relevant_migrations
示例10: getTestCaseNames
# 需要導入模塊: import functools [as 別名]
# 或者: from functools import cmp_to_key [as 別名]
def getTestCaseNames(self, testCaseClass):
"""Return a sorted sequence of method names found within testCaseClass
"""
def shouldIncludeMethod(attrname):
if not attrname.startswith(self.testMethodPrefix):
return False
testFunc = getattr(testCaseClass, attrname)
if not callable(testFunc):
return False
fullName = '%s.%s' % (testCaseClass.__module__, testFunc.__qualname__)
return self.testNamePatterns is None or \
any(fnmatchcase(fullName, pattern) for pattern in self.testNamePatterns)
testFnNames = list(filter(shouldIncludeMethod, dir(testCaseClass)))
if self.sortTestMethodsUsing:
testFnNames.sort(key=functools.cmp_to_key(self.sortTestMethodsUsing))
return testFnNames
示例11: find_median
# 需要導入模塊: import functools [as 別名]
# 或者: from functools import cmp_to_key [as 別名]
def find_median(partition, dim):
"""
find the middle of the partition, return split_val
"""
# use frequency set to get median
frequency = frequency_set(partition, dim)
split_val = ''
next_val = ''
value_list = list(frequency.keys())
value_list.sort(key=cmp_to_key(cmp_value))
total = sum(frequency.values())
middle = total // 2
if middle < GL_K or len(value_list) <= 1:
try:
return '', '', value_list[0], value_list[-1]
except IndexError:
return '', '', '', ''
index = 0
split_index = 0
for i, qi_value in enumerate(value_list):
index += frequency[qi_value]
if index >= middle:
split_val = qi_value
split_index = i
break
else:
print("Error: cannot find split_val")
try:
next_val = value_list[split_index + 1]
except IndexError:
# there is a frequency value in partition
# which can be handle by mid_set
# e.g.[1, 2, 3, 4, 4, 4, 4]
next_val = split_val
return (split_val, next_val, value_list[0], value_list[-1])
示例12: init
# 需要導入模塊: import functools [as 別名]
# 或者: from functools import cmp_to_key [as 別名]
def init(data, k, QI_num=-1):
"""
reset global variables
"""
global GL_K, RESULT, QI_LEN, QI_DICT, QI_RANGE, QI_ORDER
if QI_num <= 0:
QI_LEN = len(data[0]) - 1
else:
QI_LEN = QI_num
GL_K = k
RESULT = []
# static values
QI_DICT = []
QI_ORDER = []
QI_RANGE = []
att_values = []
for i in range(QI_LEN):
att_values.append(set())
QI_DICT.append(dict())
for record in data:
for i in range(QI_LEN):
att_values[i].add(record[i])
for i in range(QI_LEN):
value_list = list(att_values[i])
value_list.sort(key=cmp_to_key(cmp_value))
QI_RANGE.append(value(value_list[-1]) - value(value_list[0]))
QI_ORDER.append(list(value_list))
for index, qi_value in enumerate(value_list):
QI_DICT[i][qi_value] = index
示例13: getTestCaseNames
# 需要導入模塊: import functools [as 別名]
# 或者: from functools import cmp_to_key [as 別名]
def getTestCaseNames(self, testCaseClass):
"""Return a sorted sequence of method names found within testCaseClass
"""
def isTestMethod(attrname, testCaseClass=testCaseClass,
prefix=self.testMethodPrefix):
return attrname.startswith(prefix) and \
callable(getattr(testCaseClass, attrname))
testFnNames = list(filter(isTestMethod, dir(testCaseClass)))
if self.sortTestMethodsUsing:
testFnNames.sort(key=functools.cmp_to_key(self.sortTestMethodsUsing))
return testFnNames
示例14: get
# 需要導入模塊: import functools [as 別名]
# 或者: from functools import cmp_to_key [as 別名]
def get(self):
for slug, data in self.data.items():
sorted_versions = sorted(data["versions"], key=cmp_to_key(SemverCmp))
self.data[slug]["latest_version"] = sorted_versions[-1]
return self.data
示例15: _FileFamilyStyleWeights
# 需要導入模塊: import functools [as 別名]
# 或者: from functools import cmp_to_key [as 別名]
def _FileFamilyStyleWeights(fontdir):
"""Extracts file, family, style, weight 4-tuples for each font in dir.
Args:
fontdir: Directory that supposedly contains font files for a family.
Returns:
List of fonts.FileFamilyStyleWeightTuple ordered by weight, style
(normal first).
Raises:
OSError: If the font directory doesn't exist (errno.ENOTDIR) or has no font
files (errno.ENOENT) in it.
RuntimeError: If the font directory appears to contain files from multiple
families.
"""
if not os.path.isdir(fontdir):
raise OSError(errno.ENOTDIR, 'No such directory', fontdir)
files = glob.glob(os.path.join(fontdir, '*.[ot]tf'))
if not files:
raise OSError(errno.ENOENT, 'no font files found')
result = [fonts.FamilyStyleWeight(f) for f in files]
def _Cmp(r1, r2):
return cmp(r1.weight, r2.weight) or -cmp(r1.style, r2.style)
result = sorted(result, key=cmp_to_key(_Cmp))
family_names = {i.family for i in result}
if len(family_names) > 1:
raise RuntimeError('Ambiguous family name; possibilities: %s'
% family_names)
return result