回答編集履歴
3
余ったものも平均を求める処理を追加
test
CHANGED
@@ -45,3 +45,17 @@
|
|
45
45
|
return [sum(ls[i:i+n])/n for i in range(0,len(ls),n)]
|
46
46
|
|
47
47
|
```
|
48
|
+
|
49
|
+
n 個に満たない余ったものを余った個数で平均して
|
50
|
+
|
51
|
+
n_mean([1,2,3,4,5,6,7,8,9,10], 3) を [2.0, 5.0, 8.0, 10.0] としたい場合は
|
52
|
+
|
53
|
+
```Python
|
54
|
+
|
55
|
+
def n_mean(ls, n):
|
56
|
+
|
57
|
+
ln = len(ls)
|
58
|
+
|
59
|
+
return [sum(ls[i:i+n])/(n if i+n <= ln else ln-i) for i in range(0, ln, n)]
|
60
|
+
|
61
|
+
```
|
2
コードを戻して処理の差分を追記
test
CHANGED
@@ -4,9 +4,7 @@
|
|
4
4
|
|
5
5
|
def n_mean(ls, n):
|
6
6
|
|
7
|
-
|
7
|
+
return [sum(ls[i-n+1:i+1])/n for i in range(n-1,len(ls),n)]
|
8
|
-
|
9
|
-
return [sum(ls[i:i+n])/n for i in range(0,len(ls),n)] # ppaul さんのご指摘を反映
|
10
8
|
|
11
9
|
|
12
10
|
|
@@ -23,3 +21,27 @@
|
|
23
21
|
plt.show()
|
24
22
|
|
25
23
|
```
|
24
|
+
|
25
|
+
n 個の平均を取る仕様が曖昧なのでどちらがいいかわかりませんが n 個ずつにした余りを無視して
|
26
|
+
|
27
|
+
n_mean([1,2,3,4,5,6,7,8,9,10], 3) を [2.0, 5.0, 8.0] としたい場合は
|
28
|
+
|
29
|
+
```Python
|
30
|
+
|
31
|
+
def n_mean(ls, n):
|
32
|
+
|
33
|
+
return [sum(ls[i-n+1:i+1])/n for i in range(n-1,len(ls),n)]
|
34
|
+
|
35
|
+
```
|
36
|
+
|
37
|
+
n 個に満たないものも n で割った平均値にして
|
38
|
+
|
39
|
+
n_mean([1,2,3,4,5,6,7,8,9,10], 3) を [2.0, 5.0, 8.0, 3.333...] としたい場合は
|
40
|
+
|
41
|
+
```Python
|
42
|
+
|
43
|
+
def n_mean(ls, n):
|
44
|
+
|
45
|
+
return [sum(ls[i:i+n])/n for i in range(0,len(ls),n)]
|
46
|
+
|
47
|
+
```
|
1
ppaul さんのご指摘を反映
test
CHANGED
@@ -4,7 +4,9 @@
|
|
4
4
|
|
5
5
|
def n_mean(ls, n):
|
6
6
|
|
7
|
-
return [sum(ls[i-n+1:i+1])/n for i in range(n-1,len(ls),n)]
|
7
|
+
#return [sum(ls[i-n+1:i+1])/n for i in range(n-1,len(ls),n)]
|
8
|
+
|
9
|
+
return [sum(ls[i:i+n])/n for i in range(0,len(ls),n)] # ppaul さんのご指摘を反映
|
8
10
|
|
9
11
|
|
10
12
|
|