0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

pythonの引数にlambda関数を使うと便利だった

Last updated at Posted at 2023-09-20
データ
numbers = [['1', '40'], ['4', '13'], ['3', '14'], ['25', '30'], ['17', '20'], ['21', '22']]

リストの要素をキーとして最大値のリストを取得

  • リストの1つ目の要素をキーとして最大値のリストを取得
m = max(numbers, key=lambda x: int(x[0]))
print(m)
実行結果
['25', '30']
  • リストの2つ目の要素をキーとして最大値のリストを取得
m = max(numbers, key=lambda x: int(x[1]))
print(m)
実行結果
['1', '40']

リストの要素をキーとして昇順に並び替える

  • リストの1つ目の要素をキーとして昇順に並び替える
s = sorted(numbers, key=lambda x: int(x[0]))
print(s)
実行結果
[['1', '40'], ['3', '14'], ['4', '13'], ['17', '20'], ['21', '22'], ['25', '30']]
  • リストの2つ目の要素をキーとして昇順に並び替える
s = sorted(numbers, key=lambda x: int(x[0]))
print(s)
実行結果
[['4', '13'], ['3', '14'], ['17', '20'], ['21', '22'], ['25', '30'], ['1', '40']]

リストの要素の一部を取得

  • リストの1つ目の要素が2で割り切れるリストを取得
f = list(filter(lambda x: int(x[0]) % 2 == 0, numbers))
print(f)
実行結果
[['4', '13']]
  • リストの2つ目の要素が2で割り切れるリストを取得
f = list(filter(lambda x: int(x[1]) % 2 == 0, numbers))
print(f)
実行結果
[['1', '40'], ['3', '14'], ['25', '30'], ['17', '20'], ['21', '22']]

補足

こんなことも一応はできる

  • リストの2つ目の要素が2で割り切れるリストを取得し、リストの2つ目の要素をキーとして昇順に並び替える
f = sorted(list(filter(lambda x: int(x[1]) % 2 == 0, numbers)), key=lambda x: int(x[1]))
print(f)
実行結果
[['3', '14'], ['17', '20'], ['21', '22'], ['25', '30'], ['1', '40']]
0
1
0

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
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?