Python-2つのリストに共通の要素があるかどうかを確認します
Pythonリストを使用してデータを操作しているときに、2つのリストが完全に異なるのか、共通の要素があるのかを知る必要がある状況に遭遇します。これは、2つのリストの要素を、以下に説明するアプローチと比較することでわかります。
使用中
forループでは、in句を使用して、要素がリストに存在するかどうかをチェックインします。このロジックを拡張して、最初のリストから要素を選択し、2番目のリストにその要素が存在することを確認して、リストの要素を比較します。したがって、このチェックを行うためにforループをネストします。
例
#Declaring lists
list1=['a',4,'%','d','e']
list2=[3,'f',6,'d','e',3]
list3=[12,3,12,15,14,15,17]
list4=[12,42,41,12,41,12]
# In[23]:
#Defining function to check for common elements in two lists
def commonelems(x,y):
common=0
for value in x:
if value in y:
common=1
if(not common):
return ("The lists have no common elements")
else:
return ("The lists have common elements")
# In[24]:
#Checking two lists for common elements
print("Comparing list1 and list2:")
print(commonelems(list1,list2))
print("\n")
print("Comparing list1 and list3:")
print(commonelems(list1,list3))
print("\n")
print("Comparing list3 and list4:")
print(commonelems(list3,list4)) 上記のコードを実行すると、次の結果が得られます
出力
Comparing list1 and list2: The lists have common elements Comparing list1 and list3: The lists have no common elements Comparing list3 and list4: The lists have common elements
セットの使用
2つのリストに共通の要素がある場合に見つける別のアプローチは、セットを使用することです。セットには、一意の要素の順序付けられていないコレクションがあります。したがって、リストをセットに変換してから、指定されたセットを組み合わせて新しいセットを作成します。それらにいくつかの共通の要素がある場合、新しいセットは空になりません。
例
list1=['a',4,'%','d','e']
list2=[3,'f',6,'d','e',3]
# Defining function two check common elements in two lists by converting to sets
def commonelem_set(z, x):
one = set(z)
two = set(x)
if (one & two):
return ("There are common elements in both lists:", one & two)
else:
return ("There are no common elements")
# Checking common elements in two lists for
z = commonelem_set(list1, list2)
print(z)
def commonelem_any(a, b):
out = any(check in a for check in b)
# Checking condition
if out:
return ("The lists have common elements.")
else:
return ("The lists do not have common elements.")
print(commonelem_any(list1, list2)) 上記のコードを実行すると、次の結果が得られます
出力
('There are common elements in both lists:', {'d', 'e'})
The lists have common elements. -
PythonPandas-要素がIntervalに属しているかどうかを確認します
要素がIntervalに属しているかどうかを確認するには、inプロパティを使用します。まず、必要なライブラリをインポートします- import pandas as pd 時間間隔を作成する interval = pd.Interval(left=0, right=10) 間隔を表示する print("Interval...\n",interval) 間隔内に要素が存在するかどうかを確認します print("\nThe specific element exists in the Interval? = \n",6 in interval) 例
-
グラフに共通の到達可能なノードがあるかどうかをPythonでチェックするプログラム
有向グラフのエッジリストがあり、ノードがn個あり、ノード名が0〜n-1であるとします。2つの整数値aとbもあります。 cからaに、またcからbに移動できるようなノードcがあるかどうかを確認する必要があります。 したがって、入力が次のような場合 また、a =2、b =3の場合、出力はTrueになります。これは、ここではc =0であるため、0から2、さらには0から3へのルートがあります。 これを解決するには、次の手順に従います- 関数DFS()を定義します。これは、グラフ、ノード、訪問済みを取得します ノードにアクセスしていない場合は、 ノードを訪問済みとしてマーク グラフ[ノード]