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

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

More than 5 years have passed since last update.

統計モデル用の特徴行列を作る時に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')]
wwacky
Why not register and get more from Qiita?
  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