我正在尝试为练习编写代码,虽然它可以正常工作,但它看起来很可怕,我想知道是否有人可以帮我删除任何不必要的东西,并且可能只是结合了一些功能?
以下是使用该功能的一个示例:
choices([['YES', 'NO', 'YES', 'YES'], ['NO', 'NO', 'YES', 'NO'], ['YES', 'YES', 'YES', 'YES']])
列表中的每个列表都有四个是/否选择(下面的INDICES列出了四个选项,例如绿色,红色,蓝色,黄色;但它不一定是四个)。列表中的列表数量是投票人数。
i = 0
num = 0
total_num = 0
num_choices = len(INDICES)
choices_index = 0
choices_votes = []
choices_votes_num = []
index = 0
total_choices = []
winning_choice = ''
winning_index = 0
while i < len(parameter):
while num < num_choices:
for item in parameter:
choices_votes.append(item[num])
num += 1
i += 1
while total_num < len(choices_votes):
if choices_votes[total_num] == 'YES':
choices_votes_num.append(1)
total_num += 1
elif choices_votes[total_num] == 'NO':
choices_votes_num.append(0)
total_num += 1
while choices_index < len(choices_votes_num):
count = int(len(choices_votes_num) / num_choices)
total = 0
total = sum(choices_votes_num[choices_index:(choices_index + count)])
total_choices.append(total)
choices_index = choices_index + count
for score in total_choices:
winning_index = max(total_choices)
winning_choice = INDEX_TO_NAME[total_choices.index(winning_index)]
return winning_choice, total_choices
INDEX_TO_NAME
只是一个字典,用于将索引连接到选项(颜色)。
基本上,代码应该将每个yes计为1个点,每个不作为零点,将每个可用选项的总点数相加,然后返回总计和赢家。
答案 0 :(得分:4)
让我们从:
开始c = [['YES', 'NO', 'YES', 'YES'],
['NO', 'NO', 'YES', 'NO'],
['YES', 'YES', 'YES', 'YES']]
INDICES = ['red', 'green', 'blue', 'yellow']
由于您使用INDICES
来完成投票,我们可以假设答案始终与INDICES
的数字对齐。
我们可以使用zip
来重新组织这些数据:
zip(*c)
#[('YES', 'NO', 'YES'),
# ('NO', 'NO', 'YES'),
# ('YES', 'YES', 'YES'),
# ('YES', 'NO', 'YES')]
这扩展了参数的答案,并重新组合它们按实际索引进行分组。所以第一个索引是'红色',第二个是'绿色'等等
现在我们可以再次压缩以将它们与索引结合起来:
results = zip(INDICES, zip(*c))
#[('red', ('YES', 'NO', 'YES')),
# ('green', ('NO', 'NO', 'YES')),
# ('blue', ('YES', 'YES', 'YES')),
# ('yellow', ('YES', 'NO', 'YES'))]
我们可以循环results
,只计算'YES'的出现次数:
totals = [(ind, answers.count('YES')) for ind,answers in results]
#[('red', 2), ('green', 1), ('blue', 3), ('yellow', 2)]
所以这里有总数。我们可以通过调用max
来告诉我们哪一个是赢家:
max(totals, key=lambda x: x[1])
#('blue', 3)
默认情况下, max
会查看第一个索引,因此我们可以传递一个key
函数来指示它拉取索引1
。它告诉我们蓝色是赢家。
为了提高效率,我们实际上可以将生成器传递给max
:
totals = ((ind, answers.count('YES')) for ind,answers in results)
#<generator object <genexpr> at 0x102581fa0>
max(totals, key=lambda x: x[1])
#('blue', 3)
最终的单一陈述可以这样写:
max(((ind, answers.count('YES')) for (ind,answers) in zip(INDICES, zip(*c))),
key=lambda x: x[1])
我知道这个答案介绍了一些列表理解和lambda(和生成器),但是你想要一种方法来清理它,这是你可以使用的工具的一个例子。希望这能为您提供所需的帮助!
注意:这个答案没有考虑到平局。但我相信您可以从这里开始将这些示例集成到您的实际代码中