LoginSignup
0
0

More than 3 years have passed since last update.

python dictとsorted関数について

Last updated at Posted at 2020-07-02

pythonの勉強をしていると、sorted関数とはは避けて通れないものです。しかもよく忘れるので、メモっておきますね。ここは辞書に対してsorted関数を使っています。
気をつけるべきポイントはlambdaの後ろのyやxは別に何でもいいということです。例えば、lambda aaa:aaa[0]としても構わないのです。なぜなら、ここのyやxはただ前のlistの(例ではlistA, listB, listCのことです)中身なのですから。ここさえ押さえておけば大丈夫そうですよね。
以下の例を見てみてください。

listA = [3, 6, 1, 0, 10, 8, 9]
print(sorted(listA))
#结果1
#[0, 1, 3, 6, 8, 9, 10]

listB = ['g', 'e', 't', 'b', 'a']
print(sorted(listB))
print(sorted(listB, key=lambda y: y[0]))
#结果2
#['a', 'b', 'e', 'g', 't']
#['a', 'b', 'e', 'g', 't']
listC = [('e', 4), ('o', 2), ('!', 5), ('v', 3), ('l', 1)]
print(sorted(listC, key=lambda x: x[1]))
#结果3
#[('l', 1), ('o', 2), ('v', 3), ('e', 4), ('!', 5)]

sort、sortedの違いについて:
1. sortはリストの関数であるのに対し、sortedはlistのみならず、辞書dictなどのすべてのイテラブルに対して使えるのだ。
2. sortはもともとのリストを操作して、そのリストを変形させるのに対し、sortedはもともとの対象に手を加えず、新たにlistを作成してそれを戻すという作業の流れの違いはあるので、ご注意を。

さてさてまたね。

0
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0