0

我是编程新手,python 是我学习的第一门语言。

我想问的问题是如何计算列表中项目的频率,以便它们按“PARTY_INDICES”的顺序加起来?就我而言,就是这样。

这是我需要做的文档字符串:

''' (list of str) -> tuple of (str, list of int) 
votes is a list of single-candidate ballots for a single riding. 
Based on 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 votes for each party in 
the order specified in PARTY_INDICES.

>>> voting_plurality(['GREEN', 'GREEN', 'NDP', 'GREEN', 'CPC']) 
('GREEN', [1, 3, 0, 1])
'''

由于 PARTY_INDICES = [NDP_INDEX, GREEN_INDEX, LIBERAL_INDEX, CPC_INDEX] 这会产生获胜方的元组(在本例中为“GREEN”)和频率列表,其中 [1, 3, 0, 1]

这些是全局变量、列表和字典:

#  The indices where each party's data appears in a 4-element list.
NDP_INDEX = 0
GREEN_INDEX = 1
LIBERAL_INDEX = 2
CPC_INDEX = 3

# A list of the indices where each party's data appears in a 4-element list.
PARTY_INDICES = [NDP_INDEX, GREEN_INDEX, LIBERAL_INDEX, CPC_INDEX]

# A dict where each key is a party name and each value is that party's index.
NAME_TO_INDEX = {
  'NDP': NDP_INDEX,
  'GREEN': GREEN_INDEX,
  'LIBERAL': LIBERAL_INDEX,
  'CPC': CPC_INDEX
}

# A dict where each key is a party's index and each value is that party's name.
INDEX_TO_NAME = {
  NDP_INDEX: 'NDP',
  GREEN_INDEX: 'GREEN',
  LIBERAL_INDEX: 'LIBERAL',
  CPC_INDEX: 'CPC'
}

这是我的工作:

def voting_plurality(votes):
    my_list = []
    my_dct = {}
    counter = 0
    for ballot in votes:
        if (ballot in my_dct):
            my_dct[ballot] += 1
        else:
            my_dct[ballot] = 1

    if (my_dct):
        my_dct = my_dct.values()
        new_list = list(my_dct)

    return (max(set(votes), key = votes.count), new_list)

它返回:

>>> voting_plurality(['GREEN', 'GREEN', 'NDP', 'GREEN', 'CPC'])
('GREEN', [1, 1, 3])

但我希望它也包括没有投票的政党,并且符合 PARTY_INDICES [1, 3, 0, 1]

我的代码可能看起来像胡说八道,但我真的很困惑。

我也不能导入任何东西。

4

1 回答 1

0

你有两个主要问题。第一是你要占领零,但由于“自由党”没有选票,所以零不会体现出来。

提示也许您想初始化您的字典?

第二个问题是您正在调用 dict.values() ,它不会按任何顺序排列。您需要使用字典和PARTY_INDICES创建正确排序的数字列表。

提示PARTY_INDICIES也许您可以参考字典中的键以及它们在列表中的各自位置

看看您是否可以根据这些提示提出一些建议,并更新您的问题。如果你不能,我相信最终会有人发布完整的答案。

看到它已经 4 小时 - 这是一个解决方案:

def voting_plurality(votes):
    sums = dict(zip(INDEX_TO_NAME.values(), [0] * len(INDEX_TO_NAME)))
    for vote in votes:
        if vote in sums:
            sums[vote] += 1
        else:
            print "Bad vote: %s" % vote
    votes_by_index = sorted([(NAME_TO_INDEX[k], v) for k, v in sums.items()])
    votes_by_rank = sorted(votes_by_index, key=lambda x: x[1], reverse=True)
    votes_by_parts = [item[1] for item in votes_by_index]
    highest_votes = INDEX_TO_NAME[votes_by_rank[0][0]]
    return (highest_votes, votes_by_parts)
于 2012-11-22T02:49:07.313 回答