2016-11-27 36 views
-1

我被卡住了 - 需要一些帮助才能开始 - 只是碰到一堵砖墙。在python中为平均值创建函数?

所以应该有两个列表和一个表定义如下。

•参与者,演员姓名的字符串列表。对于每个i,使得0≤i≤len(Actors)-1,我们将Actor [i]称为第i个演员。

•电影,电影名称的字符串列表。对于每个i,使得0≤i≤len(Films)-1,我们将Film [i]称为第i部电影。

•分数,其行对应于演员和列的表对应于电影。分数[i] [j]是如下定义的整数。

- 如果分数[i] [j] = -1,这意味着第i个演员不是第j个电影的明星。

- 如果分数[i] [j]≥0,那么这是第j个电影的第i个演员的分数。您可以假设得分在0-100范围内,不需要检查数据的有效性。

我可以将上述结构定义为固定在我的程序中,不需要请求用户输入它们。

那么如何编写一个函数,其参数是一个整数表A和一个正整数i。该函数应该返回A [i](A的第i行)的非负项的平均值。

感谢杰马

+0

您可能需要[for循环(https://docs.python.org/3 /tutorial/controlflow.html#for-statements);这是你[定义函数](https://docs.python.org/3/tutorial/controlflow.html#defining-functions); [sum()](https://docs.python.org/3/library/functions.html#sum)会帮助你。你的表可能是一个列表清单 - 这里是[列表](工作)(https://docs.python.org/3/tutorial/introduction.html#lists)。 – wwii

+0

尝试一下。认为问题可以解决 - 参考这个问题并根据需要进行修改,将问题分解为更小的问题,然后尝试解决这些问题,回到这里解决遇到的问题,解决小问题。 stackoverflow.com/help/how-to-ask和http://stackoverflow.com/help/mcve。 – wwii

回答

1
import numpy as np 

actors = ['Brad Pitt', 'George Clooney', 'Matt Damon', 'Rowan Atkinson'] 

films = ['Oceans 11', 'Oceans 12', 'Bean'] 

actors_dimension = (len(actors)) 

longest_actor_length = len(max(actors, key=len)) 
longest_film_length = len(max(films, key=len)) 
longest_overall_length = max(longest_actor_length, longest_film_length) 
padding = longest_overall_length 

scores_width = len(films) + 1 
scores_height = len(actors) + 1 

scores = [[' '.rjust(padding) for x in range(scores_width)] for y in range(scores_height)] 

#Setting films 
for i, film in enumerate(films): 
    scores[0][i+1] = film.rjust(padding) 

#Setting actors 
for i, actor in enumerate(actors): 
    scores[i+1][0] = actor.rjust(padding) 

#Filling data 
#Brad Pitt 
scores[1][1] = '1'.rjust(padding) 
scores[1][2] = '1'.rjust(padding) 
scores[1][3] = '-1'.rjust(padding) 

#George Clooney 
scores[2][1] = '1'.rjust(padding) 
scores[2][2] = '1'.rjust(padding) 
scores[2][3] = '-1'.rjust(padding) 

'Matt Damon' 
scores[3][1] = '1'.rjust(padding) 
scores[3][2] = '1'.rjust(padding) 
scores[3][3] = '-1'.rjust(padding) 

'Rowan Atkinson' 
scores[4][1] = '-1'.rjust(padding) 
scores[4][2] = '-1'.rjust(padding) 
scores[4][3] = '1'.rjust(padding) 

def average_of_row(row): 
    if((row > actors_dimension) or (row <= 0)): 
    print('That row is not in the table or has no actor') 
    else: 
    actor = (scores[:][row]).pop(0).strip() 
    actors_scores = [int(x) for x in ((scores[:][row]))] 
    print("%s's average score is: %f" % (actor, float((sum(actors_scores)/len(actors_scores))))) 

print(np.matrix(scores)) 

average_of_row(1) #Brad Pitt 
average_of_row(4) #Rowan Atkinson 

输出:

[['    ' '  Oceans 11' '  Oceans 12' '   Bean'] 
['  Brad Pitt' '    1' '    1' '   -1'] 
['George Clooney' '    1' '    1' '   -1'] 
[' Matt Damon' '    1' '    1' '   -1'] 
['Rowan Atkinson' '   -1' '   -1' '    1']] 
Brad Pitt's average score is: 0.333333 
Rowan Atkinson's average score is: -0.333333 

试试吧here!

+0

谢谢,这真的很有帮助 - 让我思考和编码,非常感谢 – NoobyD