Skip to content

Instantly share code, notes, and snippets.

@mizunototori
Created September 13, 2016 09:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mizunototori/9750d4dcdf9d11e5ebac4a1fffc4cc98 to your computer and use it in GitHub Desktop.
Save mizunototori/9750d4dcdf9d11e5ebac4a1fffc4cc98 to your computer and use it in GitHub Desktop.
Python3系でのリスト同士の演算

Pythonでのリスト同士の演算は定義されていない。減算を例に挙げると、

  x = [10, 20, 100]
  y = [10, 15, 90]
  x - y

としたとき、

TypeError                                 Traceback (most recent call last)
<ipython-input-4-c957f021dd35> in <module>()
----> 1 x -y
TypeError: unsupported operand type(s) for -: 'list' and 'list'

というエラーとなる。

そこで、リスト同士の演算をmap関数を使って行ってみる。

list(map(lambda a,b: x - z, x,y))

出力は

 [0, 5, 10]

となる。減算をさらに、一般化させても便利かもしれない。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment