home changes contents help options

2つの配列に共通する要素を調べる

python2.3から実装された setsモジュール を使います。

 >>> import sets
 >>> programmers = sets.Set(['Jack', 'Sam', 'Susan', 'Janice'])
 >>> managers = sets.Set(['Jane', 'Jack', 'Susan', 'Zack'])
 >>> programmer_manager=programmers & managers
 >>> programmer_manager
 Set(['Jack', 'Susan'])

 >>> for i in programmer_manager:
        print i

 Jack
 Susan
 >>> import sets
 >>> a = (1, 3, 5, 6, 7, 8)
 >>> b = (2, 3, 5, 7, 9)
 >>> a_set=sets.Set(a)
 >>> b_set=sets.Set(b)
 >>> isec=a_set & b_set
 >>> isec
 Set([3, 5, 7])
 >>> list(isec)
 [3, 5, 7]

だぶりを取り除く :

 >>> union=a_set | b_set
 >>> union
 Set([1, 2, 3, 5, 6, 7, 8, 9])
 >>> list(union)
 [1, 2, 3, 5, 6, 7, 8, 9]

差をとる :

 >>> diff=a_set ^ b_set
 >>> diff
 Set([8, 1, 2, 6, 9])