当前位置: 首页>>代码示例>>Python>>正文


Python functools.cmp_to_key方法代码示例

本文整理汇总了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 
开发者ID:Soft8Soft,项目名称:verge3d-blender-addon,代码行数:25,代码来源:misc.py

示例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)) 
开发者ID:etalab,项目名称:schema.data.gouv.fr,代码行数:18,代码来源:main.py

示例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") 
开发者ID:avocado-framework,项目名称:avocado-vt,代码行数:26,代码来源:utils_disk.py

示例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 
开发者ID:CiscoTestAutomation,项目名称:genielibs,代码行数:18,代码来源:topology_mapper.py

示例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') 
开发者ID:shaise,项目名称:FreeCAD_FastenersWB,代码行数:20,代码来源:PEMInserts.py

示例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 
开发者ID:felixchenfy,项目名称:Realtime-Action-Recognition,代码行数:19,代码来源:lib_tracker.py

示例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]

#============================================================================== 
开发者ID:Microvellum,项目名称:Fluid-Designer,代码行数:20,代码来源:test_sort.py

示例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)

#============================================================================== 
开发者ID:Microvellum,项目名称:Fluid-Designer,代码行数:19,代码来源:test_sort.py

示例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 
开发者ID:hyperledger,项目名称:indy-node,代码行数:27,代码来源:migration_tool.py

示例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 
开发者ID:CedricGuillemet,项目名称:Imogen,代码行数:18,代码来源:loader.py

示例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]) 
开发者ID:qiyuangong,项目名称:Mondrian,代码行数:37,代码来源:mondrian.py

示例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 
开发者ID:qiyuangong,项目名称:Mondrian,代码行数:31,代码来源:mondrian.py

示例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 
开发者ID:war-and-code,项目名称:jawfish,代码行数:13,代码来源:loader.py

示例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 
开发者ID:etalab,项目名称:schema.data.gouv.fr,代码行数:7,代码来源:main.py

示例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 
开发者ID:googlefonts,项目名称:gftools,代码行数:34,代码来源:gftools-add-font.py


注:本文中的functools.cmp_to_key方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。