回答編集履歴
3
追記
test
CHANGED
@@ -30,7 +30,7 @@
|
|
30
30
|
|
31
31
|
フォーマット書式を省略した場合、オブジェクトの`__str__`メソッドが呼ばれます。
|
32
32
|
|
33
|
-
set_printoptionsを用いれば、指示通りの書式
|
33
|
+
numpy.set_printoptionsを用いれば、**NumPy側で**指示通りの書式を適用してくれるのです。
|
34
34
|
|
35
35
|
|
36
36
|
|
2
追記
test
CHANGED
@@ -31,3 +31,77 @@
|
|
31
31
|
フォーマット書式を省略した場合、オブジェクトの`__str__`メソッドが呼ばれます。
|
32
32
|
|
33
33
|
set_printoptionsを用いれば、指示通りの書式で文字列化してくれるのです。
|
34
|
+
|
35
|
+
|
36
|
+
|
37
|
+
実験
|
38
|
+
|
39
|
+
---
|
40
|
+
|
41
|
+
オレオレクラスで実験。
|
42
|
+
|
43
|
+
```Python
|
44
|
+
|
45
|
+
class MyArray:
|
46
|
+
|
47
|
+
def __init__(self, lst):
|
48
|
+
|
49
|
+
self._lst = lst
|
50
|
+
|
51
|
+
self._format = '{:.5f}'
|
52
|
+
|
53
|
+
|
54
|
+
|
55
|
+
def set_precision(self, precision):
|
56
|
+
|
57
|
+
self._format = '{{:.{}f}}'.format(precision)
|
58
|
+
|
59
|
+
|
60
|
+
|
61
|
+
def __str__(self):
|
62
|
+
|
63
|
+
return ' '.join(
|
64
|
+
|
65
|
+
self._format.format(e) for e in self._lst
|
66
|
+
|
67
|
+
)
|
68
|
+
|
69
|
+
|
70
|
+
|
71
|
+
|
72
|
+
|
73
|
+
arr = MyArray([3.141592, 2.718281])
|
74
|
+
|
75
|
+
print('arr is {} !'.format(arr))
|
76
|
+
|
77
|
+
|
78
|
+
|
79
|
+
arr.set_precision(3)
|
80
|
+
|
81
|
+
print('arr is {} !'.format(arr))
|
82
|
+
|
83
|
+
|
84
|
+
|
85
|
+
print('arr is {:.2f} !'.format(arr))
|
86
|
+
|
87
|
+
```
|
88
|
+
|
89
|
+
|
90
|
+
|
91
|
+
**実行結果** [Wandbox](https://wandbox.org/permlink/xDuai6VXu4fbFLpM)
|
92
|
+
|
93
|
+
```
|
94
|
+
|
95
|
+
arr is 3.14159 2.71828 !
|
96
|
+
|
97
|
+
arr is 3.142 2.718 !
|
98
|
+
|
99
|
+
Traceback (most recent call last):
|
100
|
+
|
101
|
+
File "prog.py", line 21, in <module>
|
102
|
+
|
103
|
+
print('arr is {:.2f} !'.format(arr))
|
104
|
+
|
105
|
+
TypeError: unsupported format string passed to MyArray.__format__
|
106
|
+
|
107
|
+
```
|
1
追記
test
CHANGED
@@ -21,3 +21,13 @@
|
|
21
21
|
TypeError: unsupported format string passed to list.__format__
|
22
22
|
|
23
23
|
```
|
24
|
+
|
25
|
+
|
26
|
+
|
27
|
+
> np.set_printoptions [中略] としたら、できた
|
28
|
+
|
29
|
+
|
30
|
+
|
31
|
+
フォーマット書式を省略した場合、オブジェクトの`__str__`メソッドが呼ばれます。
|
32
|
+
|
33
|
+
set_printoptionsを用いれば、指示通りの書式で文字列化してくれるのです。
|