teratail header banner
teratail header banner
質問するログイン新規登録

回答編集履歴

2

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

2020/06/14 09:01

投稿

LouiS0616
LouiS0616

スコア35678

answer CHANGED
@@ -38,16 +38,16 @@
38
38
  ```Python
39
39
  import operator
40
40
 
41
- f = operator.itemgetter(2)
41
+ func = operator.itemgetter(2)
42
- print(f(['a', 'b', 'c'])) # => c
42
+ print(func(['a', 'b', 'c'])) # => c
43
43
  ```
44
44
 
45
45
  次のうちどれを用いても、動作は全く同じです。
46
46
  ```Python
47
- def f(student):
47
+ def func(student):
48
48
  return student[2]
49
49
 
50
- sorted(student_tuples, key=f)
50
+ sorted(student_tuples, key=func)
51
51
  ```
52
52
 
53
53
  ```Python

1

追記

2020/06/14 09:01

投稿

LouiS0616
LouiS0616

スコア35678

answer CHANGED
@@ -18,4 +18,42 @@
18
18
  比較するときは15を使います。
19
19
  比較するときは12を使います。
20
20
  比較するときは10を使います。
21
+ ```
22
+
23
+ 補足1
24
+ ---
25
+ ラムダ式を変数に束縛することはあまり好まれません。
26
+ 上記のコードは説明の為の**悪い例**で、通常はこのように書きます。
27
+ ```Python
28
+ def key(student):
29
+ return student[2]
30
+ ```
31
+
32
+ ...はい、これでも全く同じように取り扱えます。
33
+ 慣れないうちはラムダ式を避け、関数定義を利用するのも一手でしょう。
34
+
35
+ 補足2
36
+ ---
37
+ リストやタプルなどの特定要素を取り出す機会は多いので、専用の関数が用意されています。
38
+ ```Python
39
+ import operator
40
+
41
+ f = operator.itemgetter(2)
42
+ print(f(['a', 'b', 'c'])) # => c
43
+ ```
44
+
45
+ 次のうちどれを用いても、動作は全く同じです。
46
+ ```Python
47
+ def f(student):
48
+ return student[2]
49
+
50
+ sorted(student_tuples, key=f)
51
+ ```
52
+
53
+ ```Python
54
+ sorted(student_tuples, key=lambda student: student[2])
55
+ ```
56
+
57
+ ```Python
58
+ sorted(student_tuples, key=operator.itemgetter(2))
21
59
  ```