LoginSignup
6
4

More than 5 years have passed since last update.

PythonでListの論理和を取る(zip関数)

Last updated at Posted at 2014-03-10

統計モデル用の特徴行列を作る時にListの論理和を取ろうとしたら、いろいろ悩んだのでメモしとく。

先に結果だけ書くと、次の様に書けばいい

>>> list1 = [1, 1, 0, 0]
>>> list2 = [1, 0, 1, 0]
>>> 
>>> #論理和
>>> [max(t) for t in zip(list1, list2)]
[1, 1, 1, 0]
>>> 
>>> #論理積
>>> [min(t) for t in zip(list1, list2)]
[1, 0, 0, 0]

上記の方法では、zip関数を使っている。
zip関数は、複数のリストをindexの位置毎にタプルにしてくれる。

>>> list1 = [1, 1, 0, 0]
>>> list2 = [1, 0, 1, 0]
>>> zip(list1, list2)
[(1, 1), (1, 0), (0, 1), (0, 0)]
>>> 
>>> #3つ以上のListでも作れる
>>> zip(['a', 'b', 'c', 'd'], ['e', 'f', 'g', 'h'], ['i', 'j', 'k', 'l'])
[('a', 'e', 'i'), ('b', 'f', 'j'), ('c', 'g', 'k'), ('d', 'h', 'l')]
>>> 
>>> #長さが異なるListが混じってる場合、最短のListの長さまでしか作られない
>>> zip(['a', 'b', 'c', 'd'], ['e', 'f', 'g', 'h'], ['i', 'j'])
[('a', 'e', 'i'), ('b', 'f', 'j')]
6
4
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
6
4