Python で 2 つのリストがある場合、次のように言います。
l1 = ['a', 'b', 'c', 'd']
l2 = ['c', 'd', 'e']
それらが同じ要素をいくつ持っているかを調べる方法はありますか。それについての場合は2になります(cとd)
ネストされたループを実行できることはわかっていますが、array_intersect 関数を使用した php のような組み込み関数はありませんか?
ありがとう
Python で 2 つのリストがある場合、次のように言います。
l1 = ['a', 'b', 'c', 'd']
l2 = ['c', 'd', 'e']
それらが同じ要素をいくつ持っているかを調べる方法はありますか。それについての場合は2になります(cとd)
ネストされたループを実行できることはわかっていますが、array_intersect 関数を使用した php のような組み込み関数はありませんか?
ありがとう
そのために設定された交差点を使用できます:)
l1 = ['a', 'b', 'c', 'd']
l2 = ['c', 'd', 'e']
set(l1).intersection(l2)
set(['c', 'd'])
>>> l1 = ['a', 'b', 'c', 'd']
>>> l2 = ['c', 'd', 'e']
>>> set(l1) & set(l2)
set(['c', 'd'])
一意の要素しかない場合は、set データ型を使用して交差を使用できます。
s1, s2 = set(l1), set(l2)
num = len(s1.intersection(s2))
セットの使用:
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