Python
 Computer >> コンピューター >  >> プログラミング >> Python

Pythonプログラム–特定の値が存在しない場合は、辞書のリストから辞書を削除します


特定の値が辞書に存在しないときに辞書のリストから辞書を削除する必要がある場合は、単純な反復、「del」演算子、および「break」ステートメントが使用されます。

以下は同じのデモンストレーションです-

my_list = [{"code" : 1, "fun" : "learn"},
   {"code" : 2, "fun" : "code"},
   {"code" : 3, "fun" : "test"},
   {"code" : 4, "fun" : "teach"},
   {"code" : 4, "fun" : "make"},
   {"code" : 4, "fun" : "object"}]

print("The list of dictionary is : " )
print(my_list)

for index in range(len(my_list)):
   if my_list[index]['code'] == 3:
      del my_list[index]
      break

print("The resultant list is : ")
print(my_list)

出力

The list of dictionary is :
[{'code': 1, 'fun': 'learn'}, {'code': 2, 'fun': 'code'}, {'code': 3, 'fun': 'test'}, {'code': 4, 'fun': 'teach'},
{'code': 4, 'fun': 'make'}, {'code': 4, 'fun': 'object'}]
The resultant list is :
[{'code': 1, 'fun': 'learn'}, {'code': 2, 'fun': 'code'}, {'code': 4, 'fun': 'teach'}, {'code': 4, 'fun': 'make'},
{'code': 4, 'fun': 'object'}]

説明

  • 文字列のリストが定義され、コンソールに表示されます。

  • リストが繰り返され、特定のインデックスが整数に等しいかどうかがチェックされます。

  • これは結果に割り当てられます。

  • これは、コンソールに出力として表示されます。


  1. Pythonで1つの値がBSTに存在するかどうかを確認するプログラム

    二分探索木とvalという別の入力があるとすると、valがツリーに存在するかどうかを確認する必要があります。 したがって、入力が次のような場合 val =7の場合、ツリーに7が存在するため、出力はTrueになります。 これを解決するために、次の手順に従います- 関数solve()を定義します。これはルートになります、val ルートがnullの場合、 Falseを返す ルートのデータがvalと同じ場合、 Trueを返す ルートのデータが

  2. リストから重複要素を削除するPythonプログラム?

    1つのリストには重複要素が含まれています。私たちのタスクは、重複なしの要素を含む別のリストを作成することです。 例 A::[2,3,4,3,4,6,78,90] Output::[2,3,4,6,78,90] アルゴリズム Step 1: create a list. Step 2: create a new list which is empty. Step 3: traverse every element in list. Step 4: if element is not present in the list return true. Step 5: append in the