📜  Python|列表中每个 n 长度连续段的平均值

📅  最后修改于: 2022-05-13 01:55:16.313000             🧑  作者: Mango

Python|列表中每个 n 长度连续段的平均值

给定一个列表,任务是找到每个长度为 n 的连续片段的平均值,其中每个片段包含 n 个元素。

例子:

Input : [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
         12, 13, 14, 15, 16, 17, 18, 19, 20]

Output: [3, 4, 5, 6, 7, 8, 9, 10, 11, 
         12, 13, 14, 15, 16, 17, 18]

Explanation:
Segment 1 - [1, 2, 3, 4, 5] => 15/5 = 3
Segment 2 - [2, 3, 4, 5, 6] => 20/5 = 4
Segment 3 - [3, 4, 5, 6, 7] => 25/5 = 5
and so on..... 


方法 #1:使用列表推导

# Python code to find average of each consecutive segment
  
# List initialisation
Input = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
         12, 13, 14, 15, 16, 17, 18, 19, 20]
  
# Defining Splits
splits = 5
  
# Finding average of each consecutive segment
Output = [sum(Input[i:i + splits])/splits
          for i in range(len(Input) - splits + 1)]
  
# printing output
print(Output)
输出:


方法#2:使用mean函数

# Python code to find average of each consecutive segment
  
# Importing
from statistics import mean
from itertools import islice
  
# List initialisation
Input = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
         12, 13, 14, 15, 16, 17, 18, 19, 20]
  
# Finding average of each consecutive segment
zip_list = zip(*(islice(Input, i, None) for i in range(5)))
Output = list(map(mean, zip_list))
  
# printing output
print(Output)
输出: