Python 基于真值表分配分数,不使用if-else结构
我有一份字典清单。每个字典都有特定的布尔标志。所以,这个列表看起来像-Python 基于真值表分配分数,不使用if-else结构,python,Python,我有一份字典清单。每个字典都有特定的布尔标志。所以,这个列表看起来像- listA = [{key1: somevalue1, key2:somevalue2, flag1:True, flag2:False, score:0}, {key1: somevalue3, key2:somevalue4, flag1:False, flag2:True, score:0}, ... {key1: somevalue(N-1), key2:some
listA = [{key1: somevalue1, key2:somevalue2, flag1:True, flag2:False, score:0},
{key1: somevalue3, key2:somevalue4, flag1:False, flag2:True, score:0},
...
{key1: somevalue(N-1), key2:somevalueN, flag1:True, flag2:False, score:0}]
假设我有一个表,它根据标志值的组合分配分数。它就像一个二元真值表:
flag1 True True False False
flag2 True False True False
score 1 2 3 4
现在,我想遍历列表,并根据它们指定的组合,将这些分数分配给列表中的每个词典。有没有一种优雅的方法来代替if-else循环?我有很多标志,每添加一个新标志,组合就会增加-结果-代码很难看 您可以使用字典来完成以下操作:
scores = {(True, True): 1, (True, False): 2,
(False, True): 3, (False, False): 4}
现在,只需查找分数[flag1,flag2]
即可找到分数
要在整个列表中执行此操作,请使用
for d in listA:
d["score"] = scores[d["flag1"], d["flag2"]]
您可以使用字典进行以下操作:
scores = {(True, True): 1, (True, False): 2,
(False, True): 3, (False, False): 4}
现在,只需查找分数[flag1,flag2]
即可找到分数
要在整个列表中执行此操作,请使用
for d in listA:
d["score"] = scores[d["flag1"], d["flag2"]]
假设您有一个函数
f
,在给定一个标志列表的情况下分配这些分数(在上面的示例中,您如何分配分数并不明显),那么您可以执行以下操作:
for myDict in myList:
score = f(myDict['flag1], myDict['flag2'])
如果要将其概括为任意数量的标志:
def score(L):
""" This function takes a list of bools and returns a score.
In this case, the score is simply the number of bools that are True """
return sum(L)
listA = [{key1: somevalue1, key2:somevalue2, flag1:True, flag2:False, score:0},
{key1: somevalue3, key2:somevalue4, flag1:False, flag2:True, score:0},
...
{key1: somevalue(N-1), key2:somevalueN, flag1:True, flag2:False, score:0}]
for d in listA:
print "The score of", d, "is:", \
score([f for f,b in d.iteritems() if type(b) == bool])
假设您有一个函数
f
,在给定一个标志列表的情况下分配这些分数(在上面的示例中,您如何分配分数并不明显),那么您可以执行以下操作:
for myDict in myList:
score = f(myDict['flag1], myDict['flag2'])
如果要将其概括为任意数量的标志:
def score(L):
""" This function takes a list of bools and returns a score.
In this case, the score is simply the number of bools that are True """
return sum(L)
listA = [{key1: somevalue1, key2:somevalue2, flag1:True, flag2:False, score:0},
{key1: somevalue3, key2:somevalue4, flag1:False, flag2:True, score:0},
...
{key1: somevalue(N-1), key2:somevalueN, flag1:True, flag2:False, score:0}]
for d in listA:
print "The score of", d, "is:", \
score([f for f,b in d.iteritems() if type(b) == bool])
哦。这看起来很简单!谢谢!!:)哦。这看起来很简单!谢谢!!:)