对常量进行分类(并能够确定其类别)

时间:2018-04-05 14:18:38

标签: python python-2.7 constants categories

我有一些常量(它们类似于错误代码)。

#errors
ERR_ROW_NUM = 1
ERR_COL_NUM = 2
ERR_NUM = 3

#incorrect
INCOR_ROW = 4
INCOR_COL = 5
INCOR_BOX = 6

#warning
WAR_HEAT = 7
WAR_PROCESS = 8

这些数字是随机的'分配并不重要(重要的是它是独一无二的)。然后我有一个字典,将常量与错误消息相关联(见下文)

MSG = {
    ERR_ROW_NUM:"incorrect number of row",
    ERR_COL_NUM:"incorrect number of column",
    ERR_NUM:"an incorrect number in tile detected",

    INCOR_ROW:"repeated number in a row",
    INCOR_COL:"repeated number in a column",
    INCOR_BOX:"repeated number in a small box",

    WAR_HEAT:"some kind of warning message",
    WAR_HARD:"the computer might not be able to handle this",
}

如您所见,常量可以分为以下类别:错误错误警告。 让我们说一个函数generate()是常数之一。如何确定'类别'来自唯一常数的常数?

我的目标是能够做到这样的事情:

output = generate()
category = #somehow get the category from the constant number
print "[ %s ] %s" % (category.upper(), MSG[output].capitalize())

因此,如果函数generate()的输出是 3 ,那么它将打印出来:

[ ERROR ] An incorrect number in tile detected

1 个答案:

答案 0 :(得分:0)

为类别创建映射:

def catMapper(cat):
    if cat in [1,2,3]:
        return "Error"  # or "ERROR" to save the .upper() below
    elif cat in [4,5,6]:
        return "..."    # Incorrect? ValidationError? pick one.
    elif cat in [7,8]:
        return "Warning"

    raise ValueError('No mapping for {}'.format(cat)) # or return a default of your liking

在创建错误消息时使用它。

print "[ %s ] %s" % (catMapper(output).upper(), MSG[output].capitalize())

您还可以将每个错误代码映射到另一个常量" CategoryType"在dict中 - 类似于你对错误消息的处理方式,但我可能会在函数内部进行,而不是在dict-lookup中进行。

使用timeit对dicts(来自@BlackJack评论的Dict-Code)的优势:

setupDict = """
CAT_TO_NAME = {cat: name for name, cats in [('Error', [1, 2, 3]), ('Incorrect', [4, 5, 6]), ('Warning', [7,8])] for cat in cats}
"""     

testDict = """
for c in range(1,9):
    getIt = CAT_TO_NAME[c]
"""

setupFunc = """
def catMapper(cat):
    if cat in [1,2,3]:
        return "Error"  # or "ERROR" to save the .upper() below
    elif cat in [4,5,6]:
        return "..."    # Incorrect? ValidationError? pick one.
    elif cat in [7,8]:
        return "Warning"

    raise ValueError('No mapping for {}'.format(cat)) # or return a default of your liking
"""

testFunc = """ 
for c in range(1,9):
    getIt = catMapper(c)
"""

import timeit

print(timeit.timeit(testDict,setup = setupDict))
print(timeit.timeit(testFunc,setup = setupFunc))

输出:

0.974066972733   # dictionary lookup
3.08595490456    # functional lookup

结果:

Dict-Lookup是高性能的3倍....查找所有代码,每次一次,100万次不是1s用于dict而3s用于功能查找。

因此,如果你的主要任务是尽可能快地查找这个字符串900万次,你可以通过使用字典来减少2s ...