gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 19:03:42 25 4
gpt4 key购买 nike

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

#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

最佳答案

为类别创建映射:

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”——类似于您对错误消息所做的操作,但我可能会在函数内部进行,而不是字典查找。


使用 timeit 的字典(字典代码取自@BlackJack 的评论)的优势:

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 万次对于 dict 和 花费不到 1s 3s 用于功能查找。

因此,如果您的主要任务是尽可能快地查找此字符串 900 万次,那么您可以通过使用字典来减少 2 秒的时间...

关于python - 对常量进行分类(并能够确定其类别),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49674654/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com