5

Python で 2 つのリストがある場合、次のように言います。

l1 = ['a', 'b', 'c', 'd']
l2 = ['c', 'd', 'e']

それらが同じ要素をいくつ持っているかを調べる方法はありますか。それについての場合は2になります(cとd)

ネストされたループを実行できることはわかっていますが、array_intersect 関数を使用した php のような組み込み関数はありませんか?

ありがとう

4

4 に答える 4

10

そのために設定された交差点を使用できます:)

l1 = ['a', 'b', 'c', 'd']
l2 = ['c', 'd', 'e']
set(l1).intersection(l2)
set(['c', 'd'])
于 2010-03-23T13:18:49.280 に答える
6
>>> l1 = ['a', 'b', 'c', 'd']
>>> l2 = ['c', 'd', 'e']
>>> set(l1) & set(l2)
set(['c', 'd'])
于 2010-03-23T13:19:26.767 に答える
5

一意の要素しかない場合は、set データ型を使用して交差を使用できます。

s1, s2 = set(l1), set(l2)
num = len(s1.intersection(s2))
于 2010-03-23T13:21:27.003 に答える
1

セットの使用:

l1 = ['a', 'b', 'c', 'd']
l2 = ['c', 'd', 'e']


def list_count_common(list_a, list_b):
    result = len(list(set(list_a) & set(list_b))) ## this is the line that does what you want
    return result

print list_count_common(l1, l2) ## prints 2
于 2010-03-23T13:29:33.620 に答える