5

番号を含むリスト (サブリスト) のリストがあり、すべての (サブ) リストに存在するものだけを保持したい。

例:

x = [ [1, 2, 3, 4], [3, 4, 6, 7], [2, 3, 4, 6, 7]]

output => [3, 4]

これどうやってするの?

4

4 に答える 4

9
common = set(x[0])
for l in x[1:]:
    common &= set(l)
print list(common)

また:

import operator
print reduce(operator.iand, map(set, x))
于 2009-11-12T15:33:42.010 に答える
7

1つのライナーで:

>>> reduce(set.intersection, x[1:], set(x[0]))
set([3, 4])
于 2009-11-12T15:35:23.960 に答える
2
def f(a, b):
    return list(set(a).intersection(set(b)))

reduce(f, x)
于 2012-12-18T11:21:46.197 に答える
1

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])
>>>
于 2014-01-30T05:29:02.287 に答える