回答編集履歴

2

f-stringと混同しかねない命名なので

2020/06/14 09:01

投稿

LouiS0616
LouiS0616

スコア35660

test CHANGED
@@ -78,9 +78,9 @@
78
78
 
79
79
 
80
80
 
81
- f = operator.itemgetter(2)
81
+ func = operator.itemgetter(2)
82
82
 
83
- print(f(['a', 'b', 'c'])) # => c
83
+ print(func(['a', 'b', 'c'])) # => c
84
84
 
85
85
  ```
86
86
 
@@ -90,13 +90,13 @@
90
90
 
91
91
  ```Python
92
92
 
93
- def f(student):
93
+ def func(student):
94
94
 
95
95
  return student[2]
96
96
 
97
97
 
98
98
 
99
- sorted(student_tuples, key=f)
99
+ sorted(student_tuples, key=func)
100
100
 
101
101
  ```
102
102
 

1

追記

2020/06/14 09:01

投稿

LouiS0616
LouiS0616

スコア35660

test CHANGED
@@ -39,3 +39,79 @@
39
39
  比較するときは10を使います。
40
40
 
41
41
  ```
42
+
43
+
44
+
45
+ 補足1
46
+
47
+ ---
48
+
49
+ ラムダ式を変数に束縛することはあまり好まれません。
50
+
51
+ 上記のコードは説明の為の**悪い例**で、通常はこのように書きます。
52
+
53
+ ```Python
54
+
55
+ def key(student):
56
+
57
+ return student[2]
58
+
59
+ ```
60
+
61
+
62
+
63
+ ...はい、これでも全く同じように取り扱えます。
64
+
65
+ 慣れないうちはラムダ式を避け、関数定義を利用するのも一手でしょう。
66
+
67
+
68
+
69
+ 補足2
70
+
71
+ ---
72
+
73
+ リストやタプルなどの特定要素を取り出す機会は多いので、専用の関数が用意されています。
74
+
75
+ ```Python
76
+
77
+ import operator
78
+
79
+
80
+
81
+ f = operator.itemgetter(2)
82
+
83
+ print(f(['a', 'b', 'c'])) # => c
84
+
85
+ ```
86
+
87
+
88
+
89
+ 次のうちどれを用いても、動作は全く同じです。
90
+
91
+ ```Python
92
+
93
+ def f(student):
94
+
95
+ return student[2]
96
+
97
+
98
+
99
+ sorted(student_tuples, key=f)
100
+
101
+ ```
102
+
103
+
104
+
105
+ ```Python
106
+
107
+ sorted(student_tuples, key=lambda student: student[2])
108
+
109
+ ```
110
+
111
+
112
+
113
+ ```Python
114
+
115
+ sorted(student_tuples, key=operator.itemgetter(2))
116
+
117
+ ```