Help us understand the problem. What is going on with this article?

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

最近競技プログラミング問題を解いているのだけど、焦っていると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の値の扱い方をうっかり忘れがちなので、気をつけたい……。

Why do not you register as a user and use Qiita more conveniently?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away