Python模块:不一致的输出

2024-06-02 08:59:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个模块,它应该找到给定向量列表的平均值。 问题是返回值不一致。有时它能给我预期的输出,有时却不能。你知道吗

def find_average_record(sen_set, voting_dict):
    """
Input: a set of last names, a voting dictionary
Output: a vector containing the average components of the voting records
        of the senators in the input set
    """

    count = len(sen_set)
    total_set = voting_dict[sen_set.pop()]

    for senator in sen_set:
        for vote in voting_dict[senator]:
            total_set[vote] += vote

    return [x/count for x in total_set]

示例:

voting_dict = {'Klein': [-1,0,1], 'Fox-Epstein': [-1,-1,-1], 'Ravella': [0,0,1]} 
find_average_record({'Fox-Epstein','Ravella'}, voting_dict) 
# should =>[-0.5, -0.5, 0.0]

Tags: oftheinforcountfindrecorddict
2条回答

这可能是错误的,因为你已经接受了马蒂恩的回答,但我认为这是你想要的。我将senator set参数更改为一个列表,以便返回的向量中的平均值与该列表的顺序相同(并且它们的数量相同)。你知道吗

def find_average_record(sen_list, voting_dict):
    """
Input: a list of senator names, a voting dictionary
Output: a vector containing the average components of the voting records
        of the senators in the input list in the same order
    """
    def average(vector):
        return sum(vector) / len(vector)

    return [average(voting_dict[senator]) for senator in sen_list]

voting_dict = {      'Klein': [-1, 0, 1],
               'Fox-Epstein': [-1,-1,-1],
                   'Ravella': [ 0, 0, 1]}
print(find_average_record(['Fox-Epstein', 'Ravella'], voting_dict))

输出:

[-1.0, 0.3333333333333333]

你用每个参议员的选票计数作为总票数的索引。别那么做。改用enumerate()。您还需要对分配给total_setvoting_dict列表进行复制,以避免更改可变列表:

def find_average_record(sen_set, voting_dict):
    count = len(sen_set)
    total_set = voting_dict[sen_set.pop()][:]

    for senator in sen_set:
        for i, vote in enumerate(voting_dict[senator]):
            total_set[i] += vote

    return [x/count for x in total_set]

您还可以在每一列上使用sum()(使用zip()来转置行和列);这样可以避免同时更改任何投票列表:

def find_average_record(sen_set, voting_dict):
    count = len(sen_set)
    return [sum(col) / count for col in zip(*(voting_dict[sen] for sen in sen_set))]

任何一个版本现在都可以正确返回平均值:

>>> find_average_record({'Fox-Epstein', 'Ravella'}, voting_dict) 
[-0.5, -0.5, 0.0]

此外,包含在voting_dict中的列表没有改变。你知道吗

相关问题 更多 >