番号を含むリスト (サブリスト) のリストがあり、すべての (サブ) リストに存在するものだけを保持したい。
例:
x = [ [1, 2, 3, 4], [3, 4, 6, 7], [2, 3, 4, 6, 7]]
output => [3, 4]
これどうやってするの?
番号を含むリスト (サブリスト) のリストがあり、すべての (サブ) リストに存在するものだけを保持したい。
例:
x = [ [1, 2, 3, 4], [3, 4, 6, 7], [2, 3, 4, 6, 7]]
output => [3, 4]
これどうやってするの?
common = set(x[0])
for l in x[1:]:
common &= set(l)
print list(common)
また:
import operator
print reduce(operator.iand, map(set, x))
1つのライナーで:
>>> reduce(set.intersection, x[1:], set(x[0]))
set([3, 4])
def f(a, b):
return list(set(a).intersection(set(b)))
reduce(f, x)
nadia とほぼ同じですが、reduce を使用せず、map を使用する別の解決方法です。
>>> x = [ [1, 2, 3, 4], [3, 4, 6, 7], [2, 3, 4, 6, 7]]
>>> set.intersection(*map(set,x))
set([3, 4])
>>>