LoginSignup
0
0

More than 3 years have passed since last update.

mapについて自分用にまとめておく

Posted at

最近競技プログラミング問題を解いているのだけど、焦っているとifやforで書きがちになるので、真の意味でmapやfilterも使える状態になっていないと気づきました。
そういった訳でよく使うJSとPythonのコードを自分用にまとめておきます。

まずはmapの基礎おさらい

Javascript
var numArray = [1,2,3];
var newArray = numArray.map(x => x*3);

console.log(newArray);//[2,4,6]

Python

Python3

numList = [1,2,3]
newList = map(str, numList)
print(list(newList))
#['1','2','3']

Pythonはmap関数の結果はリストにならないため、list()関数でリスト化など施す必要があります。
だからたとえば数値計算を施したいとき、

Python3
numList = [1,2,3]
print(map(lambda x: x*3, numList))
#<map object at 0x10aaadf28>

これだとmapのイテレータ(直接値が操作できない状態)が返ってくるため、

Python3
numList = [1,2,3]
print(list(map(lambda x: x*3, numList)))
#[3,6,9]

という具合にlist関数を通さないと、値が直接演算されません。

JSばかり弄っているとPythonの値の扱い方をうっかり忘れがちなので、気をつけたい……。

0
0
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
0