数値のリストが与えられた場合、タスクはそのリストの平均を見つけることです。平均は、要素の合計を要素の数で割ったものです。
Input : [4, 5, 1, 2] Output : 3 Explanation : Sum of the elements is 4+5+1+2 = 12 and total number of elements is 4. So average is 12/4 = 3 Input : [15, 9, 55] Output : 26.33 Explanation : Sum of the elements is 15+9+53 = 77 and total number of elements is 3. So average is 77/3 = 26.33>
Python で sum() と len() を使用したリストの平均
で パイソン、 私たちは見つけることができます 平均 sum() 関数と len() 関数を使用するだけでリストを作成できます。
- 和() : sum() 関数を使用すると、リストの合計を取得できます。
- のみ() : len() 関数は、リスト内の要素の長さまたは数を取得するために使用されます。
# Python program to get average of a list def Average(lst): return sum(lst) / len(lst) # Driver Code lst = [15, 9, 55, 41, 35, 20, 62, 49] average = Average(lst) # Printing average of the list print('Average of the list =', round(average, 2))>
出力:
Average of the list = 35.75>
時間計算量: O(n) ここで、n はリストの長さです。
補助スペース: O(1) 平均を保存するために必要な変数は 1 つだけであるためです。
Pythonでreduce()とlambdaを使用したリストの平均
使用できます 減らす() ループを軽減するには、 ラムダ関数 リストの合計を計算できます。上で説明したように、len() を使用して長さを計算します。
Python3
# Python program to get average of a list # Using reduce() and lambda # importing reduce() from functools import reduce def Average(lst): return reduce(lambda a, b: a + b, lst) / len(lst) # Driver Code lst = [15, 9, 55, 41, 35, 20, 62, 49] average = Average(lst) # Printing average of the list print('Average of the list =', round(average, 2))>
出力:
Average of the list = 35.75>
時間計算量: O(n)。n はリスト lst の長さです。
補助スペース: ○(1)。使用されるスペースは一定であり、入力リストのサイズに依存しません。
Python means() を使用したリストの平均
内蔵機能 平均() リストの平均 (average) を計算するために使用できます。
Python3
# Python program to get average of a list # Using mean() # importing mean() from statistics import mean def Average(lst): return mean(lst) # Driver Code lst = [15, 9, 55, 41, 35, 20, 62, 49] average = Average(lst) # Printing average of the list print('Average of the list =', round(average, 2))>
出力:
Average of the list = 35.75>
時間計算量: O(n)。n はリストの長さです。
補助スペース: ○(1)。
Python でリストを反復することによるリストの平均
反復 リスト for ループを使用し、リストの各要素に対して操作を実行します。
Python3 # Python code to get average of list def Average(lst): sum_of_list = 0 for i in range(len(lst)): sum_of_list += lst[i] average = sum_of_list/len(lst) return average # Driver Code lst = [15, 9, 55, 41, 35, 20, 62, 49] average = Average(lst) print('Average of the list =', round(average, 2))>
出力:
Average of the list = 35.75>
時間計算量: の上)
補助スペース: O(n)、n はリストの長さです。
Python numpy.average() 関数を使用したリストの平均
見つけることができます 平均 Python での Average() 関数を使用したリストの取得 NumPyモジュール 。
Python3 # importing numpy module import numpy # function for finding average def Average(lst): # average function avg = numpy.average(lst) return(avg) # input list lst = [15, 9, 55, 41, 35, 20, 62, 49] # function call print('Average of the list =', round(Average(lst), 2))>
出力:
Average of the list = 35.75>