如何在不使用if语句的情况下缩短此代码

时间:2012-11-24 22:18:53

标签: python python-3.x python-2.7

CONSTANTS:

NDP_INDEX = 0
GREEN_INDEX = 1
LIBERAL_INDEX = 2
CPC_INDEX = 3

各方的数据出现在4个元素列表中的索引符号。

PARTY_INDICES = [NDP_INDEX, GREEN_INDEX, LIBERAL_INDEX, CPC_INDEX]

一个字典,其中每个键都是一个聚会名称,每个值都是该聚会的索引。

NAME_TO_INDEX = {'NDP': NDP_INDEX,
'GREEN': GREEN_INDEX,'LIBERAL': LIBERAL_INDEX,'CPC': CPC_INDEX}

一个字典,其中每个键都是一方的索引,每个值都是该方的名称。

INDEX_TO_NAME = {NDP_INDEX: 'NDP',GREEN_INDEX: 'GREEN', LIBERAL_INDEX:
'LIBERAL',CPC_INDEX: 'CPC'}


def voting_range(range_votes):
    ''' 
(list of list of int) -> tuple of (str, list of int)
#range_votes is a list of integers of range ballots for a single
#riding; the order of the inner list elements corresponds to the order
#of the parties in PARTY_INDICES.Based on range_votes, return a tuple
#where the first element is the name of the party winning the seat and
#the second is a list with the total range_votes for each party in the
#order specified in PARTY_INDICES.

>>> voting_range([[5, 4, 1, 4], [3, 2, 2, 5], [3, 3, 1, 4,]])
('CPC', [11, 9, 4, 13])

'''

NDP_count = 0
GREEN_count = 0
LIBERAL_count = 0

for sub_list in range_votes:
    NDP_count += sub_list[0]
    GREEN_count += sub_list[1]
    LIBERAL_count += sub_list[2]
    CPC_count += sub_list[3]

PARTY_INDICES[0] = NDP_count
PARTY_INDICES[1] = GREEN_count
PARTY_INDICES[2] = LIBERAL_count
PARTY_INDICES[3] = CPC_count

winner = max(NDP_count, GREEN_count, LIBERAL_count, CPC_count)
if winner == NDP_count:
    return 'NDP', PARTY_INDICES
elif winner == GREEN_count:
    return 'GREEN', PARTY_INDICES
elif winner == LIBERAL_count:
    return 'LIBERAL', PARTY_INDICES
elif winner == CPC_count:
    return 'CPC', PARTY_INDICES

我不知道如何使用辅助函数来缩短它,因为我们不允许创建新的常量(通用变量)而只是局部变量

2 个答案:

答案 0 :(得分:2)

试试这个:

for sub_list in range_votes:
   for i in range(4):
       PARTY_INDICES[i] += sub_list[i]
return ( {PARTY_INDICES[0] : 'NDP', PARTY_INDICES[1] : 'GREEN', ...}[max(PARTY_INDICES)], 
         PARTY_INDICES )

这就像我愿意做的那么短; - )

答案 1 :(得分:1)

您不需要所有这些dicts和范围变量以及定义/枚举查找内容。这是一个更少的C和更多的python:

votes=[[5, 4, 1, 4], [3, 2, 2, 5], [3, 3, 1, 4,]]
parties=['NDP','GREEN','LIBERAL','CPC']

def voting_range(v):
  totals = [sum(x) for x in zip(*v)] # transpose row/col of list of lists
  pname = parties[totals.index(max(totals))]
  return (pname,totals)

>>> voting_range(votes)
('CPC',[11, 9, 4, 13])

这里有一些神奇的python事情。 *v解包列表列表,并将它们作为单独的参数提供给zip,它返回一个迭代,它给出列表中每个参数的第一个元素,然后是列表中每个参数的第二个元素, 等等。这具有转置矩阵(交换行和列)的效果。在这种形式中,简单地将每个列表相加将是投票总数。括号中包含的for x in语法是list comprehension,这是另一个非常棒的python功能,它可以从迭代中有效地创建列表。最后,indexlist method,它将返回具有指定值的第一个元素的索引,在本例中为最大值。由于v的元素应与参与方的数量具有相同的长度,因此这也将作为参与方列表的索引。